224

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?

jww
  • 97,681
  • 90
  • 411
  • 885
Supertux
  • 8,088
  • 10
  • 42
  • 47

22 Answers22

294
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.

caf
  • 233,326
  • 40
  • 323
  • 462
  • This isn't very accurate. It includes the memory used by shared libraries. – Paul Biggar Aug 03 '09 at 10:29
  • 6
    The assumption would be that if you care about a single processes' memory usage enough to monitor it like this, it's using a significant amount of memory so that the extra couple-of-megabytes due to shared mappings isn't an issue. – caf Aug 03 '09 at 11:14
  • 5
    @Chaitanya: pipe it through `| tail -n +2` – caf Nov 28 '12 at 07:24
  • 13
    Or you could use --noheader – hexacyanide Jan 26 '13 at 18:02
  • 57
    Keep in mind that %cpu "is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage" (see manpage of `ps`). This is _not_ the real just in time CPU usage. It can also be very different from what `top` shows, for instance. – xebeche Mar 27 '13 at 17:23
  • 16
    as said from Xebeche just above, `ps -e -o pcpu,args` will show the cpu average over the lifetime of the process, which is obviously not what you want if it is a long running process – Alex F Mar 01 '14 at 10:13
  • 2
    `while true; do ps -p 20283 -o %cpu,%mem,cmd; sleep 1; done;` Get a continuous status every second. – cizixs Apr 01 '15 at 02:01
  • 1
    What if the process is very short-lived? – Olle Härstedt Sep 09 '15 at 20:31
  • @OlleHärstedt: Well, in that case it's probably pretty uninteresting. You could find the total CPU time used by running it under `time`, for memory you'd need to use a memory profiler like valgrind's massif tool. – caf Sep 09 '15 at 22:18
  • Does the command return cpu usage percentage of all cores? For example if I got 30% cpu usage and I have 10 cores, it means that 3 cores are busy? Thanks. – Evgeny Dec 28 '16 at 15:40
  • 1
    @EvgenyA. No, 100% on the `%cpu` measure is one CPU (on average, over the process lifetime), so with a multithreaded process the number can be greater than 100%. – caf Dec 29 '16 at 01:20
  • 3
    This is not the cpu usage in for current situation, and it is misleading others, can you specify this point in your answer, thanks. – http8086 Nov 13 '17 at 14:33
  • what should I do if I have multiple `pid`s – alper Aug 24 '22 at 09:24
  • @cizixs, why not use watch -n1 'ps -p -o %cpu,%mem,cmd' instead of the while loop? – bvargo Feb 27 '23 at 23:18
78

A variant of caf's answer: top -p <pid>

This auto-refreshes the CPU usage so it's good for monitoring.

Community
  • 1
  • 1
Manki
  • 3,779
  • 4
  • 25
  • 18
68

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

vikyd
  • 1,807
  • 1
  • 19
  • 28
44

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.

Mez
  • 24,430
  • 14
  • 71
  • 93
amit
  • 5,079
  • 2
  • 17
  • 12
41

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
Alexey Zimarev
  • 17,944
  • 2
  • 55
  • 83
Neon
  • 1,030
  • 9
  • 12
  • 3
    thanks for pointing out `pidstat` that's a great command, and handy too for scripting! – fduff Jan 29 '15 at 15:40
  • `pidstat` also gives a nice average. just a shame i have not found a more elegant way of `pidstat -u 1 10 | grep ^Average | sort -r -n -b -k 8,8` – northern-bradley Dec 31 '19 at 18:10
21

Launch a program and monitor it

This form is useful if you want to benchmark an executable easily:

topp() (
  if [ -n "$O" ]; then
    $* &
  else
    $* &>/dev/null &
  fi
  pid="$!"
  trap "kill $pid" SIGINT
  o='%cpu,%mem,vsz,rss'
  printf '%s\n' "$o"
  i=0
  while s="$(ps --no-headers -o "$o" -p "$pid")"; do
    printf "$i $s\n"
    i=$(($i + 1))
    sleep "${T:-0.1}"
  done
)

Usage:

topp ./myprog arg1 arg2

Sample output:

%cpu,%mem,vsz
0  0.0  0.0 177584
1  0.0  0.1 588024
2  0.0  0.1 607084
3  0.0  0.2 637248
4  0.0  0.2 641692
5 68.0  0.2 637904
6 80.0  0.2 642832

where vsz is the total memory usage in KiB, e.g. the above had about 600MiB usage.

If your program finishes, the loop stops and we exit topp.

Alternatively, if you git Ctrl + C, the program also stops due to the trap: How do I kill background processes / jobs when my shell script exits?

The options are:

  • T=0.5 topp ./myprog: change poll interval
  • O=1 topp ./myprog: don't hide program stdout/stderr. This can be useful to help correlate at which point memory usage bursts with stdout.

ps vs top on instantaneous CPU% usage

Note that the CPU usage given by ps above is not "instantaneous" (i.e. over the last N seconds), but rather the average over the processes' entire lifetime as mentioned at: https://unix.stackexchange.com/questions/58539/top-and-ps-not-showing-the-same-cpu-result ps memory measures should be fine however.

That thread as well as: How can I determine the current CPU utilization from the shell? suggest that the Linux kernel does not store any more intermediate usage statistics, so the only way to do that would be to poll and calculate for the previous period, which is what top does.

We could therefore use top -n1 instead of ps if we wanted that:

toppp() (
  $* &>/dev/null &
  pid="$!"
  trap exit SIGINT
  i=1
  top -b n1 -d "${T:-0.1}" -n1 -p "$pid"
  while true; do top -b n1 -d "${T:-0.1}" -n1 -p "$pid"  | tail -1; printf "$i "; i=$(($i + 1)); done
)

as mentioned e.g. at: https://stackoverflow.com/a/62421136/895245 which produces output of type:


top - 17:36:59 up  9:25, 12 users,  load average: 0.32, 1.75, 2.21
Tasks:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
%Cpu(s): 13.4 us,  2.5 sy,  0.0 ni, 84.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
MiB Mem :  31893.7 total,  13904.3 free,  15139.8 used,   2849.7 buff/cache
MiB Swap:      0.0 total,      0.0 free,      0.0 used.  16005.5 avail Mem

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
 706287 ciro      20   0  590436  40352  20568 R 106.7   0.1   0:00.16 node
 706287 ciro      20   0  607060  57172  21340 R 126.7   0.2   0:00.35 node
1  706287 ciro      20   0  642008  80276  21812 R 113.3   0.2   0:00.52 node
2  706287 ciro      20   0  641676  93108  21812 R 113.3   0.3   0:00.70 node
3  706287 ciro      20   0  647892  99956  21812 R 106.7   0.3   0:00.87 node
4  706287 ciro      20   0  655980 109564  21812 R 140.0   0.3   0:01.09 node

Some related threads:

My only problems with this is that top is not as nice for interactive usage:

  • Ctrl + C does not exit the above command, not sure why trap exit is not working as it does with ps. I have to kill the command Ctrl + \, and then that does not kill the process itself which continues to run on the background, which means that if it is an infinite loop like a server, I have to ps aux and then kill it.
  • the not exit automatically when the benchmarked program exits

Maybe someone more shell savvy than me can find a solution for those.

ps memory measurements should be the same as top however if you're just after memory.

Related:

Tested on Ubuntu 21.10.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
6

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
Community
  • 1
  • 1
aviranh
  • 103
  • 1
  • 3
5

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.

Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
4

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.

ZhaoGang
  • 4,491
  • 1
  • 27
  • 39
4

The following command gets the average of CPU and memory usage every 40 seconds for a specific process(pid)

pidstat 40 -ru -p <pid>

Output for my case(first two lines for CPU usage, second two lines for memory):

02:15:07 PM       PID    %usr %system  %guest    %CPU   CPU  Command
02:15:47 PM     24563    0.65    0.07    0.00    0.73     3  java

02:15:07 PM       PID  minflt/s  majflt/s     VSZ    RSS   %MEM  Command
02:15:47 PM     24563      6.95      0.00 13047972 2123268   6.52  java
Celik
  • 2,311
  • 2
  • 32
  • 54
3
ps aux | awk '{print $4"\t"$11}' | sort | uniq -c | awk '{print $2" "$1" "$3}' | sort -nr

or per process

ps aux | awk '{print $4"\t"$11}' | sort | uniq -c | awk '{print $2" "$1" "$3}' | sort -nr |grep mysql
Patel95
  • 139
  • 1
2

All of the answers here show only the memory percentage for the PID.

Here's an example of how to get the rss memory usage in KB for all apache processes, replace "grep apache" with "grep PID" if you just want to watch a specific PID:

watch -n5 "ps aux -y | grep apache | awk '{print \$2,\$6}'"

This prints:

Every 5.0s: ps aux -y | grep apache | awk '{print $2,$6}'                                                                                                                                                                                                          
Thu Jan 25 15:44:13 2018

12588 9328
12589 8700
12590 9392
12591 9340
12592 8700
12811 15200
15453 9340
15693 3800
15694 2352
15695 1352
15697 948
22896 9360

With CPU %:

watch -n5 "ps aux -y | grep apache | awk '{print \$2,\$3,\$6}'"

Output:

Every 5.0s: ps aux -y | grep apache | awk '{print $2,$3,$6}'                                                                                                                                                                                                       
Thu Jan 25 15:46:00 2018

12588 0.0 9328
12589 0.0 8700
12590 0.0 9392
12591 0.0 9340
12592 0.0 8700
12811 0.0 15200
15453 0.0 9340
15778 0.0 3800
15779 0.0 2352
15780 0.0 1348
15782 0.0 948
22896 0.0 9360
Banana
  • 159
  • 2
  • 5
1

To get the memory usage of just your application (as opposed to the shared libraries it uses, you need to use the Linux smaps interface). This answer explains it well.

Community
  • 1
  • 1
Paul Biggar
  • 27,579
  • 21
  • 99
  • 152
1

(If you are in MacOS 10.10, try the accumulative -c option of top:

top -c a -pid PID

(This option is not available in other linux, tried with Scientific Linux el6 and RHEL6)

Kieleth
  • 476
  • 5
  • 12
1
ps aux|awk  '{print $2,$3,$4}'|grep PID

where the first column is the PID,second column CPU usage ,third column memory usage.

VMAtm
  • 27,943
  • 17
  • 79
  • 125
Osama Al-Banna
  • 1,465
  • 5
  • 20
  • 33
1
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 ...

Siva KR
  • 11
  • 2
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"

Tom Wocken
  • 11
  • 2
1

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
Val
  • 21,938
  • 10
  • 68
  • 86
1

Based on this answer we can estimate the average CPU and memory utilization of a specific process for a specific amount of time by collecting N samples with sampling period T as follows:

N=3;
T=1;
PROCESS_NAME="my_proc";

top -b -c -n $(let tmp=N+1; echo $tmp) -d ${T} -p $(pgrep ${PROCESS_NAME}) | 
grep ${PROCESS_NAME} |  
tee /var/tmp/foo.log |
tail -n +2 | 
awk -v N=$N 'BEGIN{
                c=0; 
                m=0
            }{
                c=c+$9; 
                m=m+$10
            }END{
                printf("%s %s\n", c/N, m/N) 
            }';

In order to be able to evaluate the results we are collecting the output of the top into the /var/tmp/foo.log file. The expected output is something like this:

2.33333 6.9

And the content of our log file:

196918 root      20   0   24.4g   1.3g 113872 S   0.0   6.9  39:58.15 my_proc
196918 root      20   0   24.4g   1.3g 113872 S   2.0   6.9  39:58.17 my_proc
196918 root      20   0   24.4g   1.3g 113872 S   3.0   6.9  39:58.20 my_proc
196918 root      20   0   24.4g   1.3g 113872 S   2.0   6.9  39:58.22 my_proc

Note that we ignore (tail -n +2) the first execution of the top command.

funk
  • 2,221
  • 1
  • 24
  • 23
1

I use htop

sudo apt install htop
htop

Press F3 to search the process you are interested in and remember the PID. Quit with q and start htop again showing the process you want only

htop -p $PID
Katu
  • 1,296
  • 1
  • 24
  • 38
0

Above list out the top cpu and memory consuming process

        ps axo %cpu,%mem,command | sort -nr | head
user8854776
  • 173
  • 1
  • 7
0

Based on @Neon answer, my two cents here:

pidstat -h -r -u -v -p $(ps aux | grep <process name> | awk '{print $2}' | tr '\n' ',')
Evhz
  • 8,852
  • 9
  • 51
  • 69