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 real-time cpu usage in output. Please help me to improve my command.
If you can afford a delay of one second, this will print CPU usage as a simple percentage:
(Without the one-second delay,
vmstat
can only print average values since boot.)This is a known issue with
top
. As explained here, the 1st iteration oftop -b
returns the percentages since boot, we therefore need at least two iterations (-n 2
) to get the current percentage. To speed things up, you can set thed
elay between iterations to0.01
.top
splits CPU usage between user, system processes andnice
processes, we want the sum of the three. Finally, yougrep
the line containing the CPU percentages and then usegawk
to sum user, system and nice processes:I have tried several ways, but this seems to me the most accurate:
Got it from here
I needed CPU usage per core and used mpstat from the sysstat package.
CPU0 Utilization in %:
CPU1 Utilization in %:
Change the -P X if you have more than 2 cores.
Use
-n2
. This will output two lines. The 1st timetop
prints the line does not qualify for the state at that point in time. Then adjust your script to ignore the first line.With a very small delay (500 ms approx), the current CPU usage in % can be found out using the following command