获取CPU使用率脚本

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

#!/bin/bash

#gino
#20150711
CPULOG_1=`cat /proc/stat | head -n1 | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}'`
SYS_IDLE_1=`echo $CPULOG_1 | awk '{print $4}'`
Total_1=`echo $CPULOG_1 | awk '{print $1+$2+$3+$4+$5+$6+$7}'`

sleep 1

CPULOG_2=`cat /proc/stat | head -n1 | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}'`
SYS_IDLE_2=`echo $CPULOG_2 | awk '{print $4}'`
Total_2=`echo $CPULOG_2 | awk '{print $1+$2+$3+$4+$5+$6+$7}'`

Total=`expr $Total_2 - $Total_1`

SYS_IDLE=`expr $SYS_IDLE_2 - $SYS_IDLE_1`


SYS_USAGE=`echo $SYS_IDLE/$Total*100 |bc -l`

SYS_Rate=`echo 100-$SYS_USAGE |bc -l`


Disp_SYS_Rate=`expr "scale=2; $SYS_Rate/1" |bc`

printf "%4.2f%%\n" ${Disp_SYS_Rate}



总结:
总CPU使用率的计算公式
CPU时间=user+system+nice+idle+iowait+irq+softirq+steal
CPU时间片=CPU_2 - CPU_1
IDLE时间=idle_2 - idle_1
CPU总的使用率=100*(CPU时间片-IDLE时间)/CPU时间片