This question is covered here in great detail.
How do you measure the memory usage of an application or process in Linux?
From the blog article of Understanding memory usage on Linux, ps
is not an accurate tool to use for this intent.
Why
ps
is "wrong"Depending on how you look at it,
ps
is not reporting the real memory usage of processes. What it is really doing is showing how much real memory each process would take up if it were the only process running. Of course, a typical Linux machine has several dozen processes running at any given time, which means that the VSZ and RSS numbers reported byps
are almost definitely wrong.
If the process is not using up too much memory (either because you expect this to be the case, or some other command has given this initial indication), and the process can withstand being stopped for a short period of time, you can try to use the gcore command.
Check the size of the generated core file to get a good idea how much memory a particular process is using.
This won't work too well if process is using hundreds of megs, or gigs, as the core generation could take several seconds or minutes to be created depending on I/O performance. During the core creation the process is stopped (or "frozen") to prevent memory changes. So be careful.
Also make sure the mount point where the core is generated has plenty of disk space and that the system will not react negatively to the core file being created in that particular directory.
Three more methods to try:
ps aux --sort pmem
It sorts the output by
%MEM
.ps aux | awk '{print $2, $4, $11}' | sort -k2r | head -n 15
It sorts using pipes.
top -a
It starts top sorting by
%MEM
(Extracted from here)
Another vote for valgrind here, but I would like to add that you can use a tool like Alleyoop to help you interpret the results generated by valgrind.
I use the two tools all the time and always have lean, non-leaky code to proudly show for it ;)
What about
time
?Not the Bash builtin
time
but the one you can find withwhich time
, for example/usr/bin/time
Here's what it covers, on a simple
ls
:Hard to tell for sure, but here are two "close" things that can help.
will give you Virtual Size (VSZ)
You can also get detailed stats from /proc file-system by going to
/proc/$pid/status
The most important is the VmSize, which should be close to what
ps aux
gives.Valgrind is amazing if you have the time to run it.
valgrind --tool=massif
is The Right Solution.However, I'm starting to run larger examples, and using valgrind is no longer practical. Is there a way to tell the maximum memory usage (modulo page size and shared pages) of a program?
On a real unix system,
/usr/bin/time -v
works. On Linux, however, this does not work.