Alex Rivera | Logout

How can I know how much memory an STL object takes?

Asked 2011-09-16T17:51:22.547
14

I need to gather statistics about memory usage in my program.

My code is mostly written using STL.

Is there any way of learning how much memory is being consumed by an STL object?

For example,

string s1 = "hello";
string s2 = "hellohellohellohellohellohellohellohellohellohellohellohellohello";

How much memory is consumed by s1 and s2? Obviously, sizeof(string)+s1.length() is not quite accurate.

Edit
Report

2 Answers

2

I don't think it would be possible to measure for an individual container.

However, to get an overall summary, you can use the mallinfo() function (on Linux).

If you want to know where are the biggest memory hogs in your program, you can run it under valgrind with its massif memory profiler, which will give you information like "15 MB were allocated from map<my_data>::...", so you can guess how large your structures are.

answered 2011-09-16T18:06:33.383
1

You can use the Psapi for this if you want general memory usage statistics.

    #ifdef WIN32
    #include <psapi.h>
    #elif __GNUC__
        #include <sys/time.h>
        #include <sys/resource.h>
    #endif

void MemoryUsage()
{
#ifdef WIN32
    PROCESS_MEMORY_COUNTERS pmc;
    if(GetProcessMemoryInfo(GetCurrentProcess(),&pmc,sizeof(pmc)))
    {
                // do something with the values you care about
        pmc.PagefileUsage;
        pmc.PeakPagefileUsage;
        pmc.PeakWorkingSetSize;
        pmc.QuotaNonPagedPoolUsage;
        pmc.QuotaPagedPoolUsage;
        pmc.QuotaPeakNonPagedPoolUsage;
        pmc.WorkingSetSize;
        }
#else
    // I'm not a penguin
#endif
}
answered 2011-09-16T18:07:34.973

Your Answer