Linux系统的cpu利用率不像windows的任务管理器这么直观能看到。top和vmstat是一个看到cpu利用率的方式。

下面是我自己计算cpu使用率的方法,以备自己做监控视图用。

[root@Centos5 admin]# more /proc/stat

cpu  494881706 19 67370877 876689477 17202366 200116 0

cpu0 96177278 1 13815598 71114795 780840 160297 0

cpu1 55637645 2 7822250 116484226 2099600 5076 0

cpu2 55163466 2 7460892 116965069 2441533 6266 0

cpu3 59323490 2 7755772 112506339 2445624 6001 0

cpu4 57541559 2 7651880 114524670 2321514 5737 0

cpu5 56891878 3 7629496 115132164 2386230 5592 0

cpu6 56887733 3 7617390 115174187 2355772 5791 0

cpu7 57258654 1 7617597 114788022 2371250 5351 0

这个是官方对cpu对第一行数据的解释:

The  number  of  jiffies  (1/100ths of a second) that the system spent in user mode, user mode  with  low  priority (nice),  system  mode,  and  the idle task, respectively. The last value should be 100 times the  second  entry  in the uptime pseudo-file.

各个参数的具体解释:

第一排是cpu总计,下面是2个4核cpu的参数,故有8行数据。

user (494881706) 从系统启动开始累计到当前时刻,用户态的CPU时间(单位:jiffies) ,不包含 nice值为负进程。1jiffies=0.01秒

nice (19) 从系统启动开始累计到当前时刻,nice值为负的进程所占用的CPU时间(单位:jiffies)

system (67370877) 从系统启动开始累计到当前时刻,核心时间(单位:jiffies)

idle (876689477) 从系统启动开始累计到当前时刻,除硬盘IO等待时间以外其它等待时间(单位:jiffies)

iowait (17202366) 从系统启动开始累计到当前时刻,硬盘IO等待时间(单位:jiffies) ,

irq (200116) 从系统启动开始累计到当前时刻,硬中断时间(单位:jiffies)

softirq (0) 从系统启动开始累计到当前时刻,软中断时间(单位:jiffies)

CPU利用率技术脚本:

本脚本持续显示cpu的利用率。


#!/bin/bash
while(true)
do
CPU_1=$(cat /proc/stat | grep 'cpu ' | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}')
SYS_IDLE_1=$(echo $CPU_1 | awk '{print $4}')
Total01=$(echo $CPU_1 | awk '{printf "%.f",$1+$2+$3+$4+$5+$6+$7}')
sleep 2
CPU_2=$(cat /proc/stat | grep 'cpu ' | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}')
SYS_IDLE_2=$(echo $CPU_2 | awk '{print $4}')
Total_2=$(echo $CPU_2 | awk '{printf "%.f",$1+$2+$3+$4+$5+$6+$7}')
SYS_IDLE=`expr $SYS_IDLE_2 - $SYS_IDLE_1`
Total=`expr $Total_2 - $Total01`
TT=`expr $SYS_IDLE \* 100`
SYS_USAGE=`expr $TT / $Total`
SYS_Rate=`expr 100 - $SYS_USAGE`
echo "The CPU Rate : $SYS_Rate%"
echo "------------------"
done