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!
Your code is discarding the IO wait time which might effect the CPU utilization. You can refer to the following link to see what each /proc/stat/ entry corresponds to:
http://man7.org/linux/man-pages/man5/proc.5.html
Overall CPU utilization can be calculated via following formula:
CPU_Util = (user+system+nice+softirq+steal)/(user+system+nice+softirq+steal+idle+iowait)
A simple bash script that would calculate the CPU utilization over 50ms would be:
#!/system/bin/sh
# Read /proc/stat file
read cpu user nice system idle iowait irq softirq steal guest< /proc/stat
cpu_active_prev=$((user+system+nice+softirq+steal))
cpu_total_prev=$((user+system+nice+softirq+steal+idle+iowait))
usleep 50000
read cpu user nice system idle iowait irq softirq steal guest< /proc/stat
cpu_active_cur=$((user+system+nice+softirq+steal))
cpu_total_cur=$((user+system+nice+softirq+steal+idle+iowait))
cpu_util=$((100*( cpu_active_cur-cpu_active_prev ) / (cpu_total_cur-cpu_total_prev) ))
echo $cpu_util
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With