Ubuntu – How to get instant CPU load values

cpu loadserver

I have made a server-client application in which based on CPU usage and load conditions it serves a file request to user.

I am using /proc/loadavg values for this . But this utility gives values averaged out over at least 1 minute.

I want values averaged out over much lesser time like 1 second or 5 seconds.

Best Answer

How about parsing the output from mpstat from the sysstat package? You can get statistics for each processor and set the interval (below is for 2s interval).

Sample output:

$ mpstat -P ALL 2
Linux 3.5.0-19-generic (ubuntu)     11/30/2012  _x86_64_    (4 CPU)

08:34:28 AM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest   %idle
08:34:30 AM  all    1.01    0.00    1.26    0.00    0.00    0.13    0.00    0.00   97.61
08:34:30 AM    0    2.50    0.00    1.50    0.00    0.00    0.50    0.00    0.00   95.50
08:34:30 AM    1    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00
08:34:30 AM    2    1.01    0.00    3.02    0.00    0.00    0.00    0.00    0.00   95.98
08:34:30 AM    3    0.50    0.00    0.50    0.00    0.00    0.00    0.00    0.00   99.00

Alternatively, you could implement the algorithm yourself. Take a look here and here.

Another way to do it would be to monitor the difference in idle time vs other usage time in /proc/stat at defined time interval and calculate the load based on that. Here's more info on /proc/stat.