I need to get the mem usage VIRT and RES at run time of my program and display them.
What i tried so far:
getrusage (http://linux.die.net/man/2/getrusage)
int who = RUSAGE_SELF;
struct rusage usage;
int ret;
ret=getrusage(who,&usage);
cout<<usage.ru_maxrss;
but i always get 0.
Old:
New: It seems that the above does not actually work, as the kernel does not fill most of the values. What does work is to get the information from proc. Instead of parsing it oneself though, it is easier to use libproc (part of procps) as follows:
Compile with "
gcc -o getrusage getrusage.c -lproc
"The existing answers are better for how to get the correct value, but I can at least explain why getrusage isn't working for you.
man 2 getrusage:
in additional to your way
you could call system ps command and get memory usage from it output.
or read info from /proc/pid ( see PIOCPSINFO struct )
On linux, if you can afford the run time cost (for debugging), you can use valgrind with the massif tool:
http://valgrind.org/docs/manual/ms-manual.html
It is heavy weight, but very useful.
I was looking for a Linux app to measure maximum memory used. valgrind is an excellent tool, but was giving me more information than I wanted. tstime seemed to be the best tool I could find. It measures "highwater" memory usage (RSS and virtual). See this answer.
Based on Don W's solution, with fewer variables.