285

I am wondering how you can get the system CPU usage and present it in percent using bash, for example.

Sample output:

57% 

In case there is more than one core, it would be nice if an average percentage could be calculated.

16
  • 1
    @julesanchez the value needs to be piped somewhere else, hence it must be an int Commented Feb 10, 2012 at 14:34
  • 18
    A command that doesn't require sysstat: ps -A -o pcpu | tail -n+2 | paste -sd+ | bc Commented Mar 3, 2015 at 13:30
  • 31
    Reopening I don't understand why this was ruled as off-topic, could the ones who closed it please care to elaborate? Commented Sep 30, 2015 at 16:44
  • 7
    My understanding of /proc/stat is very limited, but this one-liner works good enough for me: cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v RS="" '{printf "%.2f%\n", ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5)}'. With %.2f you can control the number of decimals you want to output, and with sleep 1 you can set the time you want to average over, that is, if it does what I think it does. You can put it in a bash while loop, to test it in realtime. Commented Apr 25, 2016 at 20:26
  • 1
    Nowadays I use this: { head -n1 /proc/stat;sleep 0.2;head -n1 /proc/stat; } | awk '/^cpu /{u=$2-u;s=$4-s;i=$5-i;w=$6-w}END{print int(0.5+100*(u+s+w)/(u+s+i+w))}' Which gives the average cpu percentage over the given delay (in this example set to 200ms), returned in rounded int value (but you can also leave out the int(0.5+ part). Commented Oct 21, 2017 at 9:21

6 Answers 6

251

Take a look at cat /proc/stat

grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'

EDIT please read comments before copy-paste this or using this for any serious work. This was not tested nor used, it's an idea for people who do not want to install a utility or for something that works in any distribution. Some people think you can "apt-get install" anything.

NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup. This could be very different from the current CPU usage. To get the current value top (or similar tool) must be used.

Current CPU usage can be potentially calculated with:

awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \ <(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat) 
Sign up to request clarification or add additional context in comments.

28 Comments

But you have to install mpstat like you recommend above. Many people don't have that flexibility. cat /proc/stat then pipe is much easier than mpstat you recommend.
+1 Don't understand why parsing another utility is better than parsing /proc/stat
system + user + idle = 100%. So maybe something like: grep 'cpu ' /proc/stat | awk '{cpu_usage=($2+$4)*100/($2+$4+$5)} END {print cpu_usage "%"}'
I think that this solution doesn't show the current CPU load but the average cpu load since the CPU started.
@jlliagre, yes that's right. To calculate the CURRENT cpu usage not average, you will need to take $1 value then delay then take $1 value and see the difference. That's the current cpu usage.
|
131

You can try:

top -bn1 | grep "Cpu(s)" | \ sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | \ awk '{print 100 - $1"%"}' 

33 Comments

Every time I run this command, I get the exact same output (32.7%).
A more accurate result is given when I use top -bn2, but it takes a long time. From what I've read, this seems to be the only way to get an accurate result.
top -bn1 seems wildly inaccurate on my FC20 system. top -bn2 seems to work well.
The command in this answer appears to be written for systems where top -v returns procps-ng (e.g., Fedora). There's also procps, found on, e.g., Ubuntu and CentOS, where the command doesn't work (always indicates 100%, because parsing fails due to the line with the CPU figures being formatted differently). Here's a version that works with both implementations: top -b -n2 -p 1 | fgrep "Cpu(s)" | tail -1 | awk -F'id,' -v prefix="$prefix" '{ split($1, vs, ","); v=vs[length(vs)]; sub("%", "", v); printf "%s%.1f%%\n", prefix, 100 - v }'
Side note: on OSX, use the following: top -l 2 -n 0 -F | egrep -o ' \d*\.\d+% idle' | tail -1 | awk -F% -v prefix="$prefix" '{ printf "%s%.1f%%\n", prefix, 100 - $1 }'.
|
44

Try mpstat from the sysstat package

> sudo apt-get install sysstat Linux 3.0.0-13-generic (ws025) 02/10/2012 _x86_64_ (2 CPU) 03:33:26 PM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %idle 03:33:26 PM all 2.39 0.04 0.19 0.34 0.00 0.01 0.00 0.00 97.03 

Then some cutor grepto parse the info you need:

mpstat | grep -A 5 "%idle" | tail -n 1 | awk -F " " '{print 100 - $ 12}'a 

12 Comments

I don't beleive this shows the total CPU
I'd say it 100-%idle that's the total CPU usage (in %)
That's the percentage "not" used. This answer was good, up until the grep | tail | awk part...
I'd change the awk part to: awk -F " " '{print (100 - $12)"%"}', which gives the output formatted like he wanted, but otherwise this looks good to me.
@jordanm All truths; I was more voting it up because it works. I'd do this, personally: mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12 }'
|
37

Might as well throw up an actual response with my solution, which was inspired by Peter Liljenberg's:

$ mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12"%" }' 0.75% 

This will use awk to print out 100 minus the 12th field (idle), with a percentage sign after it. awk will only do this for a line where the 12th field has numbers and dots only ($12 ~ /[0-9]+/).

You can also average five samples, one second apart:

$ mpstat 1 5 | awk 'END{print 100-$NF"%"}' 

Test it like this:

$ mpstat 1 5 | tee /dev/tty | awk 'END{print 100-$NF"%"}' 

5 Comments

Its better to run "mpstat 2 1 |..." so that it shows stats for the last 1 second. Otherwise, by default, mpstat shows stats since beginning and that does not change much as time progresses
"mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $11"%" }'" this work for me.
@Sarang Thank you so much!! Finally I can get the results that conky is displaying as well. Unfortunately, this line is VERY slow, almost taking up to one whole second to execute.
@syntaxerror It takes exactly 2 seconds because if you look at the command help you see that the first argument is that it's the interval but it only executes once because of the second argument so it waits 2 full seconds until it returns the result.
Question is closed, so added my (similar) answer to yours :-) Hope you don't mind. Like you, I was inspired by Peter Liljenberg's answer.
17

Do this to see the overall CPU usage. This calls python3 and uses the cross-platform psutil module.

printf "%b" "import psutil\nprint('{}%'.format(psutil.cpu_percent(interval=2)))" | python3 

The interval=2 part says to measure the total CPU load over a blocking period of 2 seconds.

Sample output:

9.4% 

The python program it contains is this:

import psutil print('{}%'.format(psutil.cpu_percent(interval=2))) 

Placing time in front of the call proves it takes the specified interval time of about 2 seconds in this case. Here is the call and output:

$ time printf "%b" "import psutil\nprint('{}%'.format(psutil.cpu_percent(interval=2)))" | python3 9.5% real 0m2.127s user 0m0.119s sys 0m0.008s 

To view the output for individual cores as well, let's use this python program below. First, I obtain a python list (array) of "per CPU" information, then I average everything in that list to get a "total % CPU" type value. Then I print the total and the individual core percents.

Python program:

import psutil cpu_percent_cores = psutil.cpu_percent(interval=2, percpu=True) avg = sum(cpu_percent_cores)/len(cpu_percent_cores) cpu_percent_total_str = ('%.2f' % avg) + '%' cpu_percent_cores_str = [('%.2f' % x) + '%' for x in cpu_percent_cores] print('Total: {}'.format(cpu_percent_total_str)) print('Individual CPUs: {}'.format(' '.join(cpu_percent_cores_str))) 

This can be wrapped up into an incredibly ugly 1-line bash script like this if you like. I had to be sure to use only single quotes (''), NOT double quotes ("") in the Python program in order to make this wrapping into a bash 1-liner work:

printf "%b" \ "\ import psutil\n\ cpu_percent_cores = psutil.cpu_percent(interval=2, percpu=True)\n\ avg = sum(cpu_percent_cores)/len(cpu_percent_cores)\n\ cpu_percent_total_str = ('%.2f' % avg) + '%'\n\ cpu_percent_cores_str = [('%.2f' % x) + '%' for x in cpu_percent_cores]\n\ print('Total: {}'.format(cpu_percent_total_str))\n\ print('Individual CPUs: {}'.format(' '.join(cpu_percent_cores_str)))\n\ " | python3 

Sample output: notice that I have 8 cores, so there are 8 numbers after "Individual CPUs:":

Total: 10.15% Individual CPUs: 11.00% 8.50% 11.90% 8.50% 9.90% 7.60% 11.50% 12.30% 

For more information on how the psutil.cpu_percent(interval=2) python call works, see the official psutil.cpu_percent(interval=None, percpu=False) documentation here:

psutil.cpu_percent(interval=None, percpu=False)

Return a float representing the current system-wide CPU utilization as a percentage. When interval is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately. That means the first time this is called it will return a meaningless 0.0 value which you are supposed to ignore. In this case it is recommended for accuracy that this function be called with at least 0.1 seconds between calls. When percpu is True returns a list of floats representing the utilization as a percentage for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls.

Warning: the first time this function is called with interval = 0.0 or None it will return a meaningless 0.0 value which you are supposed to ignore.

Going further:

I use the above code in my cpu_logger.py script in my eRCaGuy_dotfiles repo.

References:

  1. Stack Overflow: How to get current CPU and RAM usage in Python?
  2. Stack Overflow: Executing multi-line statements in the one-line command-line?
  3. How to display a float with two decimal places?
  4. Finding the average of a list

Related

  1. https://unix.stackexchange.com/questions/295599/how-to-show-processes-that-use-more-than-30-cpu/295608#295608
  2. https://askubuntu.com/questions/22021/how-to-log-cpu-load

Comments

16

EDITED: I noticed that in another user's reply %idle was field 12 instead of field 11. The awk has been updated to account for the %idle field being variable.

This should get you the desired output:

mpstat | awk '$3 ~ /CPU/ { for(i=1;i<=NF;i++) { if ($i ~ /%idle/) field=i } } $3 ~ /all/ { print 100 - $field }' 

If you want a simple integer rounding, you can use printf:

mpstat | awk '$3 ~ /CPU/ { for(i=1;i<=NF;i++) { if ($i ~ /%idle/) field=i } } $3 ~ /all/ { printf("%d%%",100 - $field) }' 

2 Comments

mpstat 1 1 | awk '$3 ~ /CPU/ { for(i=1;i<=NF;i++) { if ($i ~ /%idle/) field=i } } $3 ~ /all/ { printf("%d",100 - $field) }' works great for me, thanks. note the mpstat 1 1 to ensure that the cpu usage is sampled over a second
If you have jq: mpstat -o JSON -u 1 1 | jq '.sysstat.hosts[0].statistics[0]["cpu-load"][0].idle'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.