Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to find size of memory allocated to map?

Tags:

c++

dictionary

Is there any method to find the amount/size of memory allocated to a map in c++? There is a function to find the size of the map,ie,number of entries in the map, but is there any such method for the memory. I have a map ( string, string). The sizeof() is always giving me a size of 48. Any reason why this is so? Thanks :)

like image 240
freeborn Avatar asked Jul 18 '12 08:07

freeborn


People also ask

How do you find the size of a map?

util. HashMap. size() method of HashMap class is used to get the size of the map which refers to the number of the key-value pair or mappings in the Map.

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.

Does STD map allocate memory?

An std::map is typically a self balancing binary search tree1. This is a node-based data structure, quite different to an array. Typically, the data are allocated dynamically.


2 Answers

No, there is not. However you can achieve something similar for classes that support a .size method such as strings or standard container:

template <class Key, class Value>
unsigned long mapSize(const std::map<Key,Value> &map){
    unsigned long size = sizeof(map);
    for(typename std::map<Key,Value>::const_iterator it = map.begin(); it != map.end(); ++it){
        size += it->first.size();
        size += it->second.size();
    }
    return size;
}

If you want to know the allocated memory you could use .capacity:

template <class Key, class Value>
unsigned long mapCapacity(const std::map<Key,Value> &map){
    unsigned long cap = sizeof(map);
    for(typename std::map<Key,Value>::const_iterator it = map.begin(); it != map.end(); ++it){
        cap += it->first.capacity();
        cap += it->second.capacity();
    }
    return cap;
}
like image 193
Zeta Avatar answered Oct 24 '22 03:10

Zeta


There is no easy way, but if you really must know (though... why would you?), then you can find out.

All standard library containers by default allocate using a "default allocator" which is not much more than a struct/class with a pair of wrapper functions around new and delete (which themselves are, internally, little more than wrappers around malloc and free with a little alignment and a type cast on many compilers).

If you are not happy with the default allocator for whatever reason, you can provide a custom allocator to the container template, and it will just seamlessly use that one.

If you write an allocator that increments/decrements an integer at allocation/deallocation, you know how much memory has been dynamically allocated. Add to that the value of sizeof to be super precise.

like image 21
Damon Avatar answered Oct 24 '22 02:10

Damon