This commit is contained in:
48
File/Shell/check-cpu.sh
Normal file
48
File/Shell/check-cpu.sh
Normal file
@@ -0,0 +1,48 @@
|
||||
#!/bin/bash
|
||||
|
||||
#############################################################################################
|
||||
# 用途: 检测 CPU 负载
|
||||
# 作者: 丁辉
|
||||
# 更新时间: 2024-05-10
|
||||
#############################################################################################
|
||||
|
||||
# 获取第一次 CPU 时间统计
|
||||
read -a stats1 < /proc/stat
|
||||
|
||||
# 第一次统计的总 CPU 时间
|
||||
total1=0
|
||||
for i in {1..4}; do
|
||||
total1=$((total1 + ${stats1[i]}))
|
||||
done
|
||||
|
||||
# 第一次统计的空闲 CPU 时间
|
||||
idle1=${stats1[4]}
|
||||
|
||||
# 等待一个时间间隔
|
||||
sleep 1
|
||||
|
||||
# 获取第二次 CPU 时间统计
|
||||
read -a stats2 < /proc/stat
|
||||
|
||||
# 第二次统计的总 CPU 时间
|
||||
total2=0
|
||||
for i in {1..4}; do
|
||||
total2=$((total2 + ${stats2[i]}))
|
||||
done
|
||||
|
||||
# 第二次统计的空闲 CPU 时间
|
||||
idle2=${stats2[4]}
|
||||
|
||||
# 计算总的 CPU 时间差和空闲 CPU 时间差
|
||||
total=$((total2 - total1))
|
||||
idle=$((idle2 - idle1))
|
||||
|
||||
# 避免除零错误
|
||||
if [ $total -ne 0 ]; then
|
||||
cpu_usage=$((100 * (total - idle) / total))
|
||||
else
|
||||
cpu_usage=0
|
||||
fi
|
||||
|
||||
# 输出 CPU 使用率
|
||||
echo "当前 CPU 使用率为: $cpu_usage%"
|
Reference in New Issue
Block a user