[linux] 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?

This question is related to linux shell memory-management cpu-usage

The answer is


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.


Based on @Neon answer, my two cents here:

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

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

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.


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.


(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)


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

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

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


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.


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

ps aux|awk  '{print $2,$3,$4}'|grep PID

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


Above list out the top cpu and memory consuming process

        ps axo %cpu,%mem,command | sort -nr | head

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.


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

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

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


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

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"


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


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


Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to memory-management

When to create variables (memory management) How to check if pytorch is using the GPU? How to delete multiple pandas (python) dataframes from memory to save RAM? Is there a way to delete created variables, functions, etc from the memory of the interpreter? C++ error : terminate called after throwing an instance of 'std::bad_alloc' How to delete object? Android Studio - How to increase Allocated Heap Size Implementing IDisposable correctly Calculating Page Table Size Pointer-to-pointer dynamic two-dimensional array

Examples related to cpu-usage

High CPU Utilization in java application - why? How prevent CPU usage 100% because of worker process in iis SQL Server 100% CPU Utilization - One database shows high CPU usage than others How to read the Stock CPU Usage data What is the correct Performance Counter to get CPU and Memory Usage of a Process? Get Memory Usage in Android How to calculate the CPU usage of a process by PID in Linux from C? MySQL high CPU usage Retrieve CPU usage and memory usage of a single process on Linux? How do I find out what is hammering my SQL Server?