Search code examples
linuxbashubuntucpuutilization

How to calculate CPU utilization effectively using bash?


I am trying to calculate the overall CPU utilization of a single CPU, Ubuntu system using bash. I need the overall CPU usage percent for a system monitoring script I am making. The problem is that when I use the following code the CPU utilization percent is always the same:

top -n 1 | grep "Cpu"

An alternative I found is to use the following code:

read cpu a b c previdle rest < /proc/stat
prevtotal=$((a+b+c+previdle))
sleep 0.5
read cpu a b c idle rest < /proc/stat
total=$((a+b+c+idle))
CPU=$((100*( (total-prevtotal) - (idle-previdle) ) / (total-prevtotal) ))
echo $CPU

The problem with this code is that I dont know if it's completely accurate. I have a few questions... First of all why does the first code fails? Second, is the second code reliable? If not, what code could I use to get a reliable reading of the overall CPU utilization of the system? Thanks!


Solution

  • mpstat available in the systat package is quite good

    You would have to install systat using apt-get