As in the title: given an object of type of some STL container (e.g. std::vector<int>
or std::set<MyClass>
) I would like to know their memory consumption --- that is --- how much memory is consumed to store the elements, the auxiliary data for each element and the container size. I assume that the objects stored do not allocate any additional memory.
For a std::vector<int> v
I can add:
sizeof(std::vector<int>) + v.capacity()*sizeof(int)
because vectors do not store any auxiliary data per element. But how can I do it for other containers?
I can live with non-constant time complexity.
So there is no surprise regarding std::vector. It uses 4 bytes to store each 4 byte elements. It is very efficient. However, both std::set and std::unordered_set use nearly an order of magnitude more memory than would be strictly necessary.
A map with 150 million nodes soaked up ~ 15GB, which implies the 8 byte L, 8 byte R, 8 byte int key, and 8 byte datum, totaling 32 bytes, soaked up about 2/3rds of the map's memory for internal nodes, leaving 1/3rd for leaves.
Vector itself requires either 4 bytes (32 bit) or 8 bytes (64 bits) per entry, being the pointer size. That means that a vector holding 100 million nulls would use 400 or 800 megabytes. That's not a lot of memory, but its a huge Vector.
Create your own STL allocator and track the size of the memory requests placed to it, then jsut add the size of the container itself. This article gives a good overview of creating one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With