答案1
我用这个公式计算:
result=(CurrentUse-PrevUse)*100/(CurrentTotal-PrevTotal)
这是计算 cpu [us,sys,idle] 的示例脚本。
#!/bin/bash
prev_total=0
prev_idle=0
prev_us=0
prev_sys=0
while true
do
line=$(head -n1 /proc/stat)
us=$(echo $line | awk '{print $2}')
ni=$(echo $line | awk '{print $3}')
sy=$(echo $line | awk '{print $4}')
id=$(echo $line | awk '{print $5}')
io=$(echo $line | awk '{print $6}')
irq=$(echo $line | awk '{print $7}')
si=$(echo $line | awk '{print $8}')
st=$(echo $line | awk '{print $9}')
g=$(echo $line | awk '{print $10}')
gn=$(echo $line | awk '{print $11}')
total=$(expr $us + $ni + $sy + $id + $io + $irq + $si + $st + $g + $gn)
let "diff_total=$total-$prev_total"
let "diff_idle=$id-$prev_idle"
let "diff_us=$us-$prev_us"
let "diff_sys=$sy-$prev_sys"
let "result_us=$diff_us * 100 / $diff_total"
let "result_idle=$diff_idle * 100 / $diff_total"
let "result_sys=$diff_sys * 100 / $diff_total"
echo -en "\rCpu us:$result_us% sys:$result_sys% idle:$result_idle%\b\b"
prev_total=$total
prev_idle=$id
prev_us=$us
prev_sys=$sy
sleep 1
done
输出如下:
Cpu us:1% sys:0% idle:97%