How can i estimate memory usage of std::map?

前端 未结 7 551
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 03:06

For example, I have a std::map with known sizeof(A) and sizeof(B), while map has N entries inside. How would you estimate its memory usage? I\'d say it\'s something like

7条回答
  •  有刺的猬
    2020-11-29 03:50

    I was also looking for something to calculate the size of the std::map. I have tried what was explained in Diomidis Spinellis's answer and expanded his answer over here which could be helpful to others.

    I am expanding on his answer by adding few lines of code.

    #include 
    int main(int argc, char *argv[])
    {
        std::cout << sizeof(std::_Rb_tree_node_base) << std::endl;
        return 0;
    }
    

    Outputs (On my ARM Cortex A-9 iMX6Solo-X processor running Linux [4.9.175] and compiler: arm-fslc-linux-gnueabi-gcc (GCC) 7.3.0):

    16
    

    Considering std::map, I am interested in size of ELEMENT_OVERHEAD as it grows linearly with the number of elements present in the map. ELEMENT_OVERHEAD was found to be equivalent of sizeof(std::_Rb_tree_node_base) as hence has a value of 16 for my system.

    (sizeof(A) + sizeof(B) + ELEMENT_OVERHEAD) * N + CONTAINER_OVERHEAD
    

提交回复
热议问题