Invoke and track memory usage of one process
I want to run a memory-consuming program and track its memory usage over time. The program ends in a few seconds after invoked.
This previous question suggested sysstat package . While its pidstat
utility partly does what I want, it fails to meet my 2 needs:
- It accepts a minimal interval of
1s
, but I want to measure at shorter granularity. (0.1s
should be fine) - It only tracks an existing process, while I cannot always be present to copy&paste the pid.
Are there some alternative scripts / utilities to do the invoke-and-measure job better?
This should do what you need. It gets the information from /proc/$PID/statm
and prints (from man procfs
):
size total program size
(same as VmSize in /proc/[pid]/status)
resident resident set size
(same as VmRSS in /proc/[pid]/status)
share shared pages (from shared mappings)
data data + stack
The script:
#!/usr/bin/env bash
## Print header
echo -e "Size\tResid.\tShared\tData\t%"
while [ 1 ]; do
## Get the PID of the process name given as argument 1
pidno=`pgrep $1`
## If the process is running, print the memory usage
if [ -e /proc/$pidno/statm ]; then
## Get the memory info
m=`awk '{OFS="\t";print $1,$2,$3,$6}' /proc/$pidno/statm`
## Get the memory percentage
perc=`top -bd .10 -p $pidno -n 1 | grep $pidno | gawk '{print \$10}'`
## print the results
echo -e "$m\t$perc";
## If the process is not running
else
echo "$1 is not running";
fi
done
You can then call the script, giving it a process name as input. For example:
$ memusage.sh firefox
Size Resid. Shared Data %
517193 261902 9546 400715 12.8
517193 261902 9546 400715 12.8
517193 261902 9546 400715 12.8
517193 262100 9546 400715 12.8
517193 262100 9546 400715 12.8
517193 262100 9546 400715 12.8
517209 261899 9546 400731 12.8
517209 261899 9546 400731 12.8
NOTES:
- This assumes that there is only a single running process with the name specified.
After years I found that valgrind (also) have a tool for this:
# record memory usage
$ valgrind --tool=massif bash -c "sleep 5; echo hey";
==5281== Massif, a heap profiler
==5281== Copyright (C) 2003-2015, and GNU GPL'd, by Nicholas Nethercote
==5281== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==5281== Command: bash -c sleep\ 5;\ echo\ hey
==5281==
hey
==5281==
# print the usage (5281 was the pid of bash, your filename will be different)
$ ms_print massif.out.4682
Note: valgrind does more than observing: it need to inject some code and take snapshot of memory. This may harm precision of statistics.