Retrieve CPU usage and memory usage of a single process on Linux?
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. What command can I use to get this info from the Linux command-line?
Solution 1:
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.
Solution 2:
A variant of caf's answer:
top -p <pid>
This auto-refreshes the CPU usage so it's good for monitoring.
Solution 3:
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-PIDs -
tail -1
: the last row -
awk '{print $9}'
: the 9-th column(the cpu usage number)
Solution 4:
You can get the results by the name of the process using
ps -C chrome -o %cpu,%mem,cmd
the -C
option allows you to use process name without knowing it's pid.
Solution 5:
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