I am looking for a tool that would help visualize the memory usage of an application and show what's using up most of the memory - i.e. what classes, how many objects, etc. There's a similar thread that discus开发者_Python百科ses the same issue for windows but I need to do this on linux.
Valgrind would be okay for Linux, too.
You'll want to use the Valgrind tool massif (which is the documented you've linked to). It periodically takes snapshots of your heap and produces a full stack trace of which lines of code are responsible for what percentage of heap allocations.
example.cpp:
struct Int_1 { int a; };
struct Int_2 { int a,b; };
struct Int_3 { int a,b,c; };
struct Int_4 { int a,b,c,d; };
int main(void)
{
for(int i = 0; i < 1000; ++i)
{
new Int_1(); // Line 10
new Int_2(); // Line 11
new Int_3(); // Line 12
new Int_4(); // Line 13
}
return 0;
}
You'll want to compile it with debug symbols so that massif can give you exact line numbers:
g++ -g example.cpp
Now run it under Valgrind-Massif:
valgrind --tool=massif ./a.out
This will produce a file massif.out.PID, with periodic snapshots that look like this:
#-----------
snapshot=59
#-----------
time=1487054
mem_heap_B=38384
mem_heap_extra_B=53752
mem_stacks_B=0
heap_tree=detailed
n4: 38384 (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
n0: 15344 0x4005C3: main (MemExample.cpp:13)
n0: 11520 0x4005B1: main (MemExample.cpp:12)
n0: 7680 0x40059F: main (MemExample.cpp:11)
n0: 3840 0x40058D: main (MemExample.cpp:10)
The output is interpreted as "At arbitrary time unit 1487054, there were 38384 bytes allocated on the heap". The indentation represents a hierarchical breakdown of those 38348 bytes, which you can observe the proportions to match up with the given structure sizes. With more complicated code you would see full call chains that include more methods and constructors.
The idea then is that the number of bytes next to a constructor in this output shows how many instances of that class were allocated through that particular stack trace, e.g.: Line 10 allocated 3840 bytes, which is a construction of Int_1 objects so at this point in time there were 960 instances.
精彩评论