Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure total STL container memory consumption?

Tags:

c++

stl

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.

like image 670
CygnusX1 Avatar asked Aug 25 '11 13:08

CygnusX1


People also ask

How much memory does a vector use?

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.

How much memory does map take in C++?

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.

How much memory does a C++ vector take?

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.


1 Answers

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.

like image 79
Necrolis Avatar answered Oct 15 '22 13:10

Necrolis