I want to get the CPU and memory usage of a single process on Linux - I know the PID. Hopefully, I can get it every second and write it to a CSV using the \'watch\' command
ps
command (should not use):
top
command (should use):
Use top
to get CPU usage in real time(current short interval):
top -b -n 2 -d 0.2 -p 6962 | tail -1 | awk '{print $9}'
will echo like: 78.6
-b
: Batch-mode-n 2
: Number-of-iterations, use 2
because: When you first run it, it has no previous
sample to compare to, so these initial values are the percentages since boot.-d 0.2
: Delay-time(in second, here is 200ms)-p 6962
: Monitor-PIDstail -1
: the last rowawk '{print $9}'
: the 9-th column(the cpu usage number)As commented in caf's answer above, ps and in some cases pidstat will give you the lifetime average of the pCPU. To get more accurate results use top. If you need to run top once you can run:
top -b -n 1 -p <PID>
or for process only data and header:
top -b -n 1 -p <PID> | tail -3 | head -2
without headers:
top -b -n 1 -p <PID> | tail -2 | head -1
This is a nice trick to follow one or more programs in real time while also watching some other tool's output:
watch "top -bn1 -p$(pidof foo),$(pidof bar); tool"
Use pidstat (from sysstat - Refer Link).
e.g. to monitor these two process IDs (12345 and 11223) every 5 seconds use
$ pidstat -h -r -u -v -p 12345,11223 5
ps aux|awk '{print $2,$3,$4}'|grep PID
where the first column is the PID,second column CPU usage ,third column memory usage.
Launch a program and monitor it
This form is useful if you want to benchmark an executable easily:
topp() (
$* &>/dev/null &
pid="$!"
trap ':' INT
echo 'CPU MEM'
while sleep 1; do ps --no-headers -o '%cpu,%mem' -p "$pid"; done
kill "$pid"
)
topp ./myprog arg1 arg2
Now when you hit Ctrl + C it exits the program and stops monitoring. Sample output:
CPU MEM
20.0 1.3
35.0 1.3
40.0 1.3
Related: https://unix.stackexchange.com/questions/554/how-to-monitor-cpu-memory-usage-of-a-single-process
Tested on Ubuntu 16.04.