Getting cpu usage same every time.

command linecpu

When I execute following command to get cpu usage , I get nice + user cpu usage.

top -b -n1 | grep "Cpu(s)" | awk '{print $2 + $4}' 

Output:

14.5

Here I am getting problem is that the output depends on top command thus it doesn't change instantly as top command. So I am not getting correct cpu instantly. It gives same output and not changing.

I want to get realtime cpuusage in output. Please help me to improve my command.

Best Answer

You're right, top appears to give incorrect CPU usage on first iteration. You can work around this issue like this:

top -b -n2 | grep "Cpu(s)"|tail -n 1 | awk '{print $2 + $4}'

This will of course take twice as much time, but it will work anyway.

If you still want it work faster, you can use -d option, e.g. for 1-second total period of measurement use half of it:

top -d 0.5 -b -n2 | grep "Cpu(s)"|tail -n 1 | awk '{print $2 + $4}'
Related Question