How to get the current CPU utilization on Linux?

I want to get the current CPU utilization. Here is the hard way to do it  “Literally click here.” Let’s just be honest; I have so much time in my free hands to do this.

So much homework. Oh Amy, you know my pain…

So, I cheated by using top command. What is top? Well man it yoself. Just kidding.  Top command displays the CPU utilization and verbose Linux processes periodically. In order to calculate the CPU utilization; we just subtract the CPU on idle from 100%.

screenshotSo, it’s the third line that shows the CPU utilization. Now, how are we going to pull out the data from top? Keep reading. ;)

Top has the options  “-n” and “-b”. What are those?

Straight outta MAN

-n  :Number-of-iterations limit as:  -n number
Specifies the maximum number of iterations, or frames, top should produce before ending.
-b  :Batch-mode operation
Starts top in 'Batch' mode, which could be useful for sending output from top to other programs or to a file.  In this mode, top will not accept input and runs until the iterations  limit you've set with the '-n' command-line option or until killed.

Command :

top -n 2 -b | awk '/%Cpu/{print}' | tail -1

Will return

%Cpu(s): 1.3 us, 0.2 sy, 0.0 ni, 98.5 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st

What do us, sy, ni, id, wa, hi, si, and st mean? Straight from theStacks:

us: user cpu time (or) % CPU time spent in user space
sy: system cpu time (or) % CPU time spent in kernel space
ni: user nice cpu time (or) % CPU time spent on low priority processes
id: idle cpu time (or) % CPU time spent idle
wa: io wait cpu time (or) % CPU time spent in wait (on disk)
hi: hardware irq (or) % CPU time spent servicing/handling hardware interrupts
si: software irq (or) % CPU time spent servicing/handling software interrupts
st: steal time - - % CPU time in involuntary wait by virtual cpu while hypervisor is servicing another processor (or) % CPU time stolen from a virtual machine

I know so much unnecessary information. But, whatever…

Then we subtract the CPU idle (column 8) time from 100%.

top -n 2 -b | awk '/%Cpu/{print 100-$8"%"}' | tail -1



You might be wondering why we are using -n 2 instead of -n 1. I found that using 1 for iteration doesn’t return an accurate CPU utilization; by using 2, there is an extra iteration to calculate a possibly accurate CPU utilization. Don’t believe me? Go ahead and try it. :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>