Search code examples
linuxawkgrepcut

Get CPU usage for indivudal cores in mpstat


I've been asked to grab the CPU usage for individual cores using mpstat. I can get all the information I need for each an individual CPU like so:

mpstat -P 0

Which gives the following output:

Linux 3.10.0-957.21.3.el7.x86_64 (cpu_devel)         03/16/2021      _x86_64_        (48 CPU)

09:59:32 AM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest  %gnice   %idle
09:59:32 AM    0    0.05    0.00    0.05    0.00    0.00    0.01    0.00    0.00    0.00   99.89

What I need to do is grab the number under idle (99.89) and subtract that from 100 to get the total CPU usage. I was trying to grab the 12th field with a delimiter of spaces like this:

mpstat -P 0 | cut -d' ' -f12

But that showed me that there are actually multiple spaces between each field. So I'm looking for help to find a cleaner solution!


Solution

  • You could simply do this with awk. Simply pass your command(mpstat) output as a standard input to awk command as an input; then in main program of awk look if the line number is 4th line then print last column of that line(with checking a condition if $NF is greater than 0 then subtract it with 100 else print it as it is).

    mpstat -P 0 | awk 'FNR==4{print ($NF>0?100-$NF:$NF)}'