261

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.

Kar.ma
  • 743
  • 6
  • 12
user1199739
  • 2,683
  • 2
  • 15
  • 6
  • 1
    @julesanchez the value needs to be piped somewhere else, hence it must be an int – user1199739 Feb 10 '12 at 14:34
  • doing top > myfile.txt And applying your filter in post-treatment, is not ok ? – JuSchz Feb 10 '12 at 14:35
  • If it needs to be an int, does that mean you actually don't want the % as stated in the question? – jordanm Feb 10 '12 at 15:17
  • 15
    A command that doesn't require sysstat: `ps -A -o pcpu | tail -n+2 | paste -sd+ | bc` – RFon Mar 03 '15 at 13:30
  • 21
    **Reopening** I don't understand why this was ruled as off-topic, could the ones who closed it please care to elaborate? – Jonathan H Sep 30 '15 at 16:44
  • None of these solutions worked for me so I came up with this: https://mohammadg.com/linux/how-to-get-overall-cpu-utilization-from-the-bash-command-line/ – Mo Beigi Dec 06 '15 at 11:29
  • 5
    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. – Yeti Apr 25 '16 at 20:26
  • 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). – Yeti Oct 21 '17 at 09:21
  • top -b -n 1 |grep Cpu|cut -d "," -f 4|cut -d " " -f 2 | awk '{cpu_usage=(100-$1)} END {print cpu_usage "%"}' – Zibri Nov 27 '18 at 15:57
  • Reading through the other answers it seems `awk -Fid '/Cpu/ { split($1, a, ","); print 100 - a[length(a)] "%"; }' < <(top -b)` is perhaps the most balanced between conciseness, robustness, and modification... In short there's no need of `cat`, `cut`, `grep`, `sed`, etc. – S0AndS0 Aug 09 '21 at 17:46
  • So long as this question remains close on Stack Overflow, I suggest we add new answers to this question I added here on Unix and Linux Stack Exchange: [Unix & Linux: How to get overall CPU usage (e.g. 57%) on Linux](https://unix.stackexchange.com/questions/686424/how-to-get-overall-cpu-usage-e-g-57-on-linux) – Gabriel Staples Jan 15 '22 at 01:06
  • the first and second top answers show me different values in the same machine :/ – JRichardsz Jun 18 '22 at 00:09
  • who the heck closed it again? – Reishin Jul 26 '22 at 21:49
  • @IRon your command `ps -A -o pcpu | tail -n+2` if I add up all those values sometimes I get values over 100%. I was making tests with the `stress` command for example `stress --cpu 2 --timeout 30` and the results came to be over 100% – Tono Nam Sep 08 '22 at 17:35
  • Voting to reopen. [My answer to this, for instance](https://stackoverflow.com/a/70760502/4561887), is very clearly a programming problem (ex: Python). This question is not inherently a non-programming question. – Gabriel Staples Dec 22 '22 at 04:54

6 Answers6

237

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)
Mike Q
  • 6,716
  • 5
  • 55
  • 62
vimdude
  • 4,447
  • 1
  • 25
  • 23
  • I wouldn't recommend parsing that in bash when there are a number of utilities which already do this. – jordanm Feb 10 '12 at 14:53
  • 12
    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. – vimdude Mar 22 '13 at 13:13
  • 12
    +1 Don't understand why parsing another utility is better than parsing `/proc/stat` – Reinstate Monica Please Feb 26 '14 at 18:31
  • 9
    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 "%"}' – vimdude Jun 02 '14 at 18:51
  • Works fine but I get usage value less (almost half) than the one reported by "System Moniter". I am on a dual core machine and both cores report less usage. Any reason why? – nvd Jul 15 '14 at 00:10
  • can you post the output of grep 'cpu ' /proc/stat – vimdude Jul 15 '14 at 19:53
  • @vimdude can you explain how you are calculating it? – CMCDragonkai Jul 19 '14 at 08:52
  • And how does it deal with intervals? – CMCDragonkai Jul 19 '14 at 09:32
  • 121
    I think that this solution doesn't show the current CPU load but the average cpu load since the CPU started. – Etienne Sep 11 '14 at 15:54
  • 1
    @Etienne Indeed, see http://stackoverflow.com/questions/32029015/why-does-cpu-load-not-change-more-than-a-few-hundredths/32029995#32029995 – jlliagre Aug 16 '15 at 01:16
  • 11
    @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. – vimdude Aug 19 '15 at 15:11
  • Well, that's still an average but for a shorter period of time. The current (instantaneous) CPU usage is either 0% (idle or iowait) or 100% (anything else). – jlliagre Aug 19 '15 at 15:18
  • Not really. Average would make sense if you do two delays, then sum then divide by two. – vimdude Aug 19 '15 at 15:20
  • 1
    Not only. Whatever the delay, the reported usage is an average of the actual load during it, and more precisely an estimation of the actual average as the CPU state is sampled, not accurately measured. Anything else than 0% or 100% cannot be but an average load. – jlliagre Aug 19 '15 at 16:30
  • 7
    This is a horrible answer. I can only imagine how many hapless people this has misled. Firstly, as already brought up by @Etienne and @jlliagre, these values reflect sum totals since boot. Secondly, if you're going to use them, you need to add up all of them -- i.e., `$2` through `$10` on modern kernels -- whether you're going to print them all or not. Search for explanation in `man proc` ... and then just walk away and use `mpstat`. – rsaw Jan 09 '16 at 08:28
  • @rsaw instead of going into making nasty comments like that, why don't you write your answer so people can vote and use? I will up vote you if I find your answer elegant. You should have followed the conversation and not copy paste the answer. See the part "So maybe something like ...". The answer was not used nor tested, it's an idea instead of parsing utilities like mpstat. mpstat gets the data from /proc. – vimdude Jan 13 '16 at 02:13
  • @vimdude I don't see how my comment was "nasty". It was not an attack on you as a person. For the record: I read the whole conversation before posting, but the history of it still doesn't change the facts. Kudos for the newly-added warning in the body of the answer. – rsaw Jan 17 '16 at 09:27
  • 2
    @vimdude Comments should only be temporary, please add the essential parts into your answer. – Christian Strempfer Jul 07 '16 at 14:01
  • 3
    what about: `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)` – ton Mar 17 '17 at 20:05
  • 4
    I see many complex commands but a simple command (derived from some of answers here) which seems to work for me is `top -b -n2 | grep "Cpu(s)" | awk '{print $2+$4 "%"}' | tail -n1` I compared it with CPU usage reported by Task Manager and it nearly match. – ashah Mar 24 '17 at 12:27
  • Hi @vimdude ...ur solution works for me.. Can you suggest how to use above code in php file to fetch output. – pihu May 24 '17 at 07:55
  • I wonder whether it is similar to `uptime | awk '{print $12/$(nproc)*100}'` – Vincent Vidal Jul 21 '17 at 11:52
  • 3
    This doesn't work as expected: the value doesn't correspond with the actual cpu load – ma3oun Nov 26 '17 at 19:50
  • The values are **cumulative**; you have to **remember** the values, **wait** 1 second, then get the values **again** and from the **difference** you can compute the %usage within that 1 second. – rustyx Jan 14 '20 at 13:25
  • What about replacing grep by $1 ~ /^cpu/ filter in awk? – Arĥimedeς ℳontegasppα ℭacilhας Mar 03 '20 at 16:43
  • When being called endlessly and reaching 100% CPU, it sometimes returns: `awk: cmd. (FILENAME=/dev/fd/62 FNR=1) fatal: division by zero attempted)` – iTaMaR May 15 '21 at 02:05
  • You can round the output to any decimal place with `printf` and `%.f` where is any integer. Also you can sleep .01s instead of 1s. Example: `awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else printf "%.1f", ($2+$4-u1) * 100 / (t-t1) "%"; }' <(grep 'cpu ' /proc/stat) <(sleep .1;grep 'cpu ' /proc/stat)` – Llama D'Attore Dec 17 '21 at 08:30
  • second command is working for me. how to put the 2nd command in answer behind `watch` command to be updated every 2 seconds? – Naveen Reddy Marthala Dec 25 '21 at 17:33
127

You can try:

top -bn1 | grep "Cpu(s)" | \
           sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | \
           awk '{print 100 - $1"%"}'
netcoder
  • 66,435
  • 19
  • 125
  • 142
  • 19
    Every time I run this command, I get the exact same output (`32.7%`). – alanaktion Jul 18 '13 at 01:58
  • 16
    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. – alanaktion Jul 18 '13 at 02:10
  • 7
    `top -bn1` seems wildly inaccurate on my FC20 system. `top -bn2` seems to work well. – Martin Tournoij Feb 19 '14 at 00:58
  • 1
    In my server, i need change regex: "s/.*, *\([0-9.]*\)%* -------> sed "s/.*: *\([0-9.]*\)%*.*/\1/" – Edgard Leal Feb 21 '14 at 02:12
  • 28
    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 }'` – mklement0 Feb 21 '14 at 04:15
  • 2
    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 }'`. – mklement0 Feb 21 '14 at 04:15
  • I use this using perl: top -b -n2 -p 1|perl -lane 'if( /Cpu\(s\):\s+([\d\.]+)%us,\s+([\d\.]+)%sy/){$u=$1 + $2;}END{printf("%.1f%%\n", $u);}' – sfgroups Aug 01 '14 at 22:49
  • @mklement0, does your command `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 }'` give instant CPU usage or total average CPU usage since boot? – Sagar Jha Jan 12 '15 at 00:54
  • @SagarJha: _Not_ since boot - "instant" in that the percentage reported is based on 2 current samples (1-2 secs. apart, depending on implementation) - apparently at least 2 samples are needed to get a somewhat accurate reading. – mklement0 Jan 12 '15 at 16:54
  • I found out that the only reliable way, even if it takes 1 second is to use mpstat: `mpstat 1 1 | grep 'Average' | awk '{ printf "CPU: %.0f%%", 100-$NF }'` – idragosalex May 16 '15 at 10:31
  • So, when output of `top -bn1 | grep "Cpu(s)"` is `%Cpu(s): 2,2 us, 0,6 sy, 0,0 ni, 96,XXX id, 0,6 wa, 0,1 hi, 0,0 si, 0,0 st` so the percentage is `100 - XXX`, right? – Fredrick Gauss Jul 27 '15 at 11:46
  • 1
    I use this: top -n1 -b | grep "Cpu(s):" | awk -F " " '{print $2}' | sed -e 's/us,//' – Krzysztof Jarosz Dec 16 '15 at 10:37
  • @netcoder: When I'm running that command I always get back two values. The first one is always the same (3.1%), the other one is changing. Can you explain what these values exactly mean? – arne.z Apr 10 '16 at 23:54
  • If you want to use this to get some trends over time, consider tweaking the values of `-bn` and `-d` in the call to `top`. `top -b1000 -d0.2` will give you lots of sample points close together. – ymbirtt Apr 11 '16 at 10:58
  • @FredrickGauss On a Debian system with English locale, the output looks like `...nn%ni 96.22%id mm%wa ...` and the (wasteful, ugly) processing extracts the idle number quite nicely, and subtracts that from 100. – tripleee Jun 23 '16 at 11:14
  • This is a [useless use of `grep | sed | awk`](http://www.iki.fi/era/unix/award.html#grep) which would be better written `top -bn1 | awk '/Cpu\(s\):/ { print 100-$5 }'` – tripleee Jun 23 '16 at 11:16
  • @tripleee, my system is EN locale but the output as I wrote it. – Fredrick Gauss Jun 27 '16 at 06:11
  • @FredrickGauss I find that hard to believe; in English, the decimal separator is a full stop, not a comma. Perhaps your `LC_NUMERIC` or some other aspect of your locale is non-standard. – tripleee Jun 27 '16 at 06:17
  • @tripleee, you are right. My lc_numeric is not English. But I wonder if the result like `.. 96,3 id, ..` then, should the grepping part `96,3` (in my system) ? Where does the percentage sign (`%`) come from? – Fredrick Gauss Jun 27 '16 at 11:13
  • ©FredrickGauss I see it on my system in the output from `top`. Maybe yours is much older (or newer?) or maybe that is affected by the locale, too. – tripleee Jun 27 '16 at 11:15
  • http://serverfault.com/a/436499/134517 – altendky Sep 30 '16 at 15:44
  • FWIW, `top` on Ubuntu 14.04 is in fact `procps-ng` and this command should work on Ubuntu >= 14.04 – JDS Oct 19 '16 at 15:07
  • top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%*id.*/\1/" | awk '{print 100 - $1"%"}' seems to be more correct – sadfuzzy Jan 18 '17 at 15:59
  • 1
    don't work on arch. vimdude answer works – Gelldur Jan 19 '17 at 22:24
  • I used this answer in a script – Marinaio Aug 12 '19 at 19:28
  • For those working with European numbers (ex 1,1 instead of 1.1), use this: `top -bn1 | grep "Cpu(s)" | sed -r 's/\,([0-9]{1,2})\b/.\1/g' | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1"%"}'` – Wimateeka Oct 24 '19 at 15:14
  • works on aws sagemaker instances – halil Dec 04 '19 at 15:46
  • Add -1 (`top -bn1 -1`) to view all cores =) – mazunki May 04 '20 at 18:31
  • Can be simplified into a single grep with: `top -bn1 | grep -Po "[0-9.]*(?=( id,))" | awk '{print 100 - $1"%"}'` – Mentor Oct 12 '20 at 08:06
  • @tripleee Yeah, that triggered me as well. But your solution fails when the idle time is 100% becuase `0.0 ni, 11.2 id` becomes `0.0 ni,100 id` (one less field). Thus better would be `awk -F , '/^%Cpu/{print 100-$4}'`. – Quasímodo Jun 28 '21 at 16:36
  • @Mentor That could still be simplified to `top -bn1 | awk '/ id,/ { split($0, x, / id,/); print 100-x[1] "%" }'` and remove the non-portable requirement for `grep -P`. (I'm sure it could be prettified further, too.) – tripleee Jun 28 '21 at 17:51
  • @Quasimodo but then that loses the space separator for the other fields. GNU Awk lets you specify a regex for `-F` but perhaps more usefully use `substr` to pull out a string at a fixed index. Or just preprocess to make sure every comma is followed by a space, then re-parse the line. – tripleee Jun 28 '21 at 17:56
  • 1
    this give me -23000% utilization??? – Blanket Fox May 13 '22 at 12:11
42

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
Peter Svensson
  • 6,105
  • 1
  • 31
  • 31
36

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"%"}'
PJ Brunet
  • 3,615
  • 40
  • 37
Dan Fego
  • 13,644
  • 6
  • 48
  • 59
  • 19
    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 – Sarang Jul 19 '13 at 19:56
  • 2
    "mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $11"%" }'" this work for me. – AloneInTheDark Feb 26 '14 at 09:05
  • @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 Sep 15 '14 at 01:35
  • 7
    @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. – Johan Bjäreholt Jan 30 '15 at 11:16
  • 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. – PJ Brunet Apr 22 '20 at 04:39
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) }'
jordanm
  • 33,009
  • 7
  • 61
  • 76
  • 3
    `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 – chrishiestand Jun 07 '15 at 06:28
  • 2
    If you have jq: `mpstat -o JSON -u 1 1 | jq '.sysstat.hosts[0].statistics[0]["cpu-load"][0].idle'` – nyet Mar 29 '19 at 01:21
9

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
Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265