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
For those who struggled for a while wonderring why the selected answer does not work:
ps -p <pid> -o %cpu,%mem
No SPACE ibetween %cpu,
and %mem
.
ps axo pid,etime,%cpu,%mem,cmd | grep 'processname' | grep -v grep
PID - Process ID
etime - Process Running/Live Duration
%cpu - CPU usage
%mem - Memory usage
cmd - Command
Replace processname with whatever process you want to track, mysql nginx php-fpm etc ...
CPU and memory usage of a single process on Linux or you can get the top 10 cpu utilized processes by using below command
ps -aux --sort -pcpu | head -n 11
You could use top -b
and grep out the pid you want (with the -b
flag top runs in batch mode), or also use the -p
flag and specify the pid without using grep.
Based on @caf's answer, this working nicely for me.
Calculate average for given PID:
measure.sh
times=100
total=0
for i in $(seq 1 $times)
do
OUTPUT=$(top -b -n 1 -d 0.1 -p $1 | tail -1 | awk '{print $9}')
echo -n "$i time: ${OUTPUT}"\\r
total=`echo "$total + $OUTPUT" | bc -l`
done
#echo "Average: $total / $times" | bc
average=`echo "scale=2; $total / $times" | bc`
echo "Average: $average"
Usage:
# send PID as argument
sh measure.sh 3282
ps -p <pid> -o %cpu,%mem,cmd
(You can leave off "cmd" but that might be helpful in debugging).
Note that this gives average CPU usage of the process over the time it has been running.