Retrieve CPU usage and memory usage of a single process on Linux?
ps
command (should not use):
- CPU usage is currently expressed as the percentage of time spent running during the entire lifetime of a process.
top
command (should use):
- The task's share of the elapsed CPU time since the last screen update, expressed as a percentage of total CPU time.
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, use2
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)
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.
A variant of caf's answer:
top -p <pid>
This auto-refreshes the CPU usage so it's good for monitoring.