3

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!

Lynx
  • 165
  • 1
  • 11

2 Answers2

3

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
jake
  • 71
  • 1
  • 8
1

mpstat available in the systat package is quite good

You would have to install systat using apt-get

Shamis Shukoor
  • 2,515
  • 5
  • 29
  • 33
  • I dont know if I am doing anything wrong but when I do: `while true; do; mpstat; done;` I am getting always the same value for the CPU utilization even If I am running several processes. – Lynx Nov 23 '12 at 17:16
  • Ok now I discovered that if you run the mpstat command withut any parameters the output is nonsense… it must be used like this `mpstat 1 1` – Lynx Nov 23 '12 at 17:33