need to get average idle time using mpstat

0

I want to get average idle time of the server using mpstat. The problem I am having is %idle is not in same columns in all the versions of linux.

example 1:

[root@testserver ~]# mpstat 1 2
Linux 2.6.32-358.el6.x86_64 (testserver)        06/18/2015      _x86_64_        (2 CPU)

12:41:17 AM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest   %idle
12:41:18 AM  all    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00
12:41:19 AM  all    0.50    0.00    0.50    0.00    0.00    0.00    0.00    0.00   99.00
Average:     all    0.25    0.00    0.25    0.00    0.00    0.00    0.00    0.00   99.50

example 2:

[root@testserver1 ~]# mpstat 1 2
Linux 2.6.18-308.8.2.el5 (testserver1)      06/17/2015

10:47:38 PM  CPU   %user   %nice    %sys %iowait    %irq   %soft  %steal   %idle    intr/s
10:47:39 PM  all    0.12    0.00    0.00    0.00    0.00    0.00    0.00   99.88    191.09
10:47:40 PM  all    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00    134.00
Average:     all    0.06    0.00    0.00    0.00    0.00    0.00    0.00   99.94    162.69

I tried below command as generalized solution but as Average as one less column output is not proper.

mpstat 1 2 | egrep -v '^Linux|^$' |  awk -v c="%idle" 'NR==1 {for (i=1; i<=NF; i++) if ($i==c) break}''{print $i}'

I am getting below output.

[root@testserver ~]# mpstat 1 2 | egrep -v '^Linux|^$' |  awk -v c="%idle" 'NR==1 {for (i=1; i<=NF; i++) if ($i==c) break}''{print $i}'
%idle
100.00
100.00

But the desired output is

[root@testserver ~]# mpstat 1 2 | egrep -v '^Linux|^$' |  awk -v c="%idle" 'NR==1 {for (i=1; i<=NF; i++) if ($i==c) break}''{print $i}'
%idle
100.00
100.00
100.00

Best Wishes, KJ

KumarJohn

Posted 2015-06-18T05:58:47.453

Reputation: 223

Answers

1

You can use:

awk '/%idle/ {for (i=1;i<=NF;i++) {if ($i=="%idle") col=i-1}}
     /^Average:/ {print $col}'

This stores the column where %idle is and substracts one because Average: does not have the PM/AM column. Then, it prints that column when the line starts with Average:.

Test

With sample1:

$ awk '/%idle/ {for (i=1;i<=NF;i++) {if ($i=="%idle") col=i-1}} /^Average:/ {print $col}' a
99.50

With sample2:

$ awk '/%idle/ {for (i=1;i<=NF;i++) {if ($i=="%idle") col=i-1}} /^Average:/ {print $col}' b
99.94

fedorqui

Posted 2015-06-18T05:58:47.453

Reputation: 1 517