The easiest way I know to do this is to use top
in batch mode and single iteration:
$ top -bn 1| grep Cpu
%Cpu(s): 5.0 us, 2.8 sy, 0.0 ni, 91.4 id, 0.5 wa, 0.0 hi, 0.2 si, 0.0 st
See my answer here for an explanation of the fields. Suffice it to say you want the sum of us
, sy
and ni
so some parsing is required:
$ top -bn 1| grep Cpu | gawk '{print $2+$4+$6}' > logfile
The above command returns 7.8, meaning that 7.8% of available CPU power is in use at that particular moment. You can use cron
to run that command, for example, every minute:
$ crontab -e
This will open an editor window (of whichever editor you have set as the $EDITOR
shell variable), in that window paste this line and then save and close it:
* * * * * top -bn 1| grep Cpu | gawk '{print $2+$4+$6}' >> ~/logfile
That will cause the CPU percentage to be written to ~/logfile
every two minutes.
If you want a breakdown for each CPU, you could parse the output of mpstat
:
$ mpstat -P ALL | tail -n +4 | gawk '{print "CPU:"$3,$4+$5+$6}'
CPU:all 7.87
CPU:0 10.73
CPU:1 10.75
CPU:2 4.97
CPU:3 5.09
How many CPUs do you have? Do you want a breakdown for each CPU or the overall, combined CPU usage? – terdon – 2013-05-28T17:28:30.540
I guess it would be combined, but getting an idea of each would also be helpful.
lscpu
tells me I have 8 CPU's. – MeanwhileInHell – 2013-05-28T17:34:06.267