cpu使用率计算

#!/bin/bash

#/*************************************************
# /proc/stat 文件第一行 是cpu使用情况
# t1时间采集一下cpu信息,第五列是cpu空闲时间idle1,除第一例之外的其他列之和是cpu总的时间total1
# 时间间隔1s后t2时间在采集一次,分别求出空闲时间idle2和总时间total2
# cpu使用率 = 100 - 100*(idle2 - idle1)/(total2 - total1)
# ***************************************************/
cpu_info1=$(cat /proc/stat | grep "^cpu ")
idle1=$(echo ${cpu_info1} | awk '{print $5}')
total1=$(echo ${cpu_info1} | awk 'BEGIN{sum=0}{for(i=2;i<=NF;i++){sum+=$i} {print sum}}')
sleep 1
cpu_info2=$(cat /proc/stat | grep "^cpu ")
idle2=$(echo ${cpu_info2} | awk '{print $5}')
total2=$(echo ${cpu_info2} | awk 'BEGIN{sum=0}{for(i=2;i<=NF;i++){sum+=$i} {print sum}}')
t=$(echo ${total2} - ${total1} | bc)
idle=$(echo ${idle2} - ${idle1} | bc)

cpu_used_per=$(echo "100 - 100*${idle}/${t}" | bc)

echo "cpu_used_percent: " ${cpu_used_per} "%"

猜你喜欢

转载自blog.csdn.net/xin_yun_jian/article/details/80718628
今日推荐