2

I'm just wondering whether there is a way in C++11 to get an exact estimation of the occupied memory for std::map (in bytes). For example:

std::map<int,int> m;

assume "m" has 10 elements, I want to know what the overall memory consumption is. In some posts I see the following rough estimation for this particular case:

size_t map_size = sizeof(std::map<int,int>) + m.size()*(sizeof(int)*2);

However, it does not consider the memory overhead per element, is it somehow measurable?! Thanks.

Alexey Abramov
  • 435
  • 1
  • 3
  • 16
  • 5
    "Exact estimation"? :) -- I don't see a better way than going into your standard library's header and seeing for yourself, but it's no cakewalk. – Quentin Jan 29 '18 at 12:06
  • Assuming you mean at runtime, why do you care? If you're so low on memory that the approximation of `map.size() * sizeof` isn't accurate enough, then you're probably in more trouble than you explained in your question. Perhaps you could explain why you think it's important to have such an accurate estimation – UKMonkey Jan 29 '18 at 12:17
  • Not mentioned in that dup link - you could put a custom allocator in your std::map template declaration and track the memory usage from there. – Gem Taylor Jan 29 '18 at 19:02
  • But even then, there is some system overhead in memory allocations. – Gem Taylor Jan 29 '18 at 20:39
  • I need it to compare the memory overhead for various std containers, I don't have any troubles in my programs, no worries. I'm just curious whether it is measurable. – Alexey Abramov Feb 02 '18 at 12:15
  • I will try to use a custom allocator, sounds like a good idea. – Alexey Abramov Feb 02 '18 at 12:16

0 Answers0