How to get overall CPU sage (e.g. 57%) on Linux [c

2019-01-01 12:57发布

问题:

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.

回答1:

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.



回答2:

You can try:

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


回答3:

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


回答4:

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]+/).



回答5:

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) }\'