feat:添加计算cpu利用率示例代码

This commit is contained in:
yanfeizhang
2023-01-14 19:24:51 +08:00
parent 2862e235e4
commit 62eb71dec9
3 changed files with 46 additions and 2 deletions

View File

@@ -1 +1,2 @@
- [likely 和 unlikely 汇编结果对比](tests/cpu/test01)
- [likely 和 unlikely 汇编结果对比](tests/cpu/test01)
- [cpu 系统利用率的计算过程](tests/cpu/test06)

View File

@@ -0,0 +1,40 @@
#!/bin/bash
#获取宿主机的 CPU 使用情况
function get_host_cpu_usage(){
#内核会在/proc/stat中输出整机CPU的使用情况, 例如cat /proc/stat 输出如下
#cpu 52635657 657000 57094567 7675992570 422057 0 545206 0 0 0
#其中各列中的数值都是从启动到现在的累计和单位是jiffies
#除了第一列外,其余每列的含义分别是:
# 1.user用户态花费的cpu时间
# 2.nice用户态在低优先级花费的cpu时间
# 3.system系统态花费的cpu时间
# 4.idel在空闲任务上花费的cpu时间
# 5.iowait等待I/O花费的cpu时间
# 6.irq硬中断花费的cpu时间
# 7.softirq软中断花费的cpu时间
# 8.steal系统处在虚拟化环境中你的虚拟机被其他虚拟机占用的 CPU 时间
# 9.guest运行虚拟机花费的cpu时间
# 10.guest_nice运行低优先级虚拟机花费的cpu时间
#获取宿主机的 CPU 用量的原理,是选择两个时间点,
#cpu总时间=user+system+nice+idle+iowait+irq+softirq
#cpu_usage=100-(idle2-idle1)/(cpu总时间2-cpu总时1)*100
T1_CPU_INFO=$(cat /proc/stat | grep -w cpu | awk '{print $2,$3,$4,$5,$6,$7,$8}')
T1_IDLE=$(echo $T1_CPU_INFO | awk '{print $4}')
T1_TOTAL=$(echo $T1_CPU_INFO | awk '{print $1+$2+$3+$4+$5+$6+$7}')
sleep 10
T2_CPU_INFO=$(cat /proc/stat | grep -w cpu | awk '{print $2,$3,$4,$5,$6,$7,$8}')
T2_IDLE=$(echo $T2_CPU_INFO | awk '{print $4}')
T2_TOTAL=$(echo $T2_CPU_INFO | awk '{print $1+$2+$3+$4+$5+$6+$7}')
CPU_UTILIZATION=`echo ${T1_IDLE} ${T1_TOTAL} ${T2_IDLE} ${T2_TOTAL}| awk '{printf "%.2f", (1-($3-$1)/($4-$2))*100}'`
echo "Host CPU Utiliztion:${CPU_UTILIZATION}%"
}
get_host_cpu_usage