简体   繁体   中英

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!

mpstat available in the systat package is quite good

You would have to install systat using apt-get

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM