monitor a program's memory usage in Linux
Solution 1
It's not exactly what you are looking for, but have a look at Valgrind.
Solution 2
while (/proc/<pid>/status)
echo "VMSize: `ps -p <pid> -o vsize=`" >> ! mem.out
pstack <pid> >> mem.out
sleep 10
end
grep VMSize mem.out | awk -F':' '{print $2}' | sort -r -n | head -1
will give you peak memory.
Also use mem.out to see memory footprint and current stack correlation.
Solution 3
It is really difficult to work out how much memory a process is using on an operating system which supports virtual memory.
The problem is not working out how much memory it's using, but how much of that is private and how much shared.
You can look at /proc/pid/maps or /proc/pid/smaps (maybe). These files will only tell you how much memory the process has mapped into its address space, not how much it's using, and definitely not how much is shared with other processes in the system.
Even "private" maps can be shared because fork() does copy-on-write, so a private page could still be shared with some other (related - usually parent or sibling) process. Moreover, pages which have been mapped in but never used won't be consuming space at all.
The RSS (Resident set size) of each mapping can be seen, but that only tells you how much is resident (in RAM, as opposed to swapped out into a swap file, not yet allocated, or not yet demand-loaded from a mapped file), now how much is shared and with what.
I guess your best bet would be to count the amount of private anonymous memory, which might be ok, in some cases.
Lawtonj94
Updated on June 05, 2022Comments
-
Lawtonj94 about 2 years
Are there any tools available in Linux which graphically or textually display memory usage for a program? For example, if I write a C++ program and would like to verify that objects are being allocated and deallocated properly in memory, are there applications available that would visually show the objects being instantiated and deleted? When I used to program in Visual Studio, I remember stepping through a program and using a debug pane to monitor memory usage and am looking for something similar to that in Linux.
-
Lawtonj94 over 15 yearsGood suggestion. Looks like a very useful tool!
-
Richard Corden over 15 yearsWith --tool=massif you get a visual graph of the memory usage.
-
LiraNuna over 15 years"valgrind - your new best friend"