我有一个以百分比计算 CPU 使用率的 shell 脚本。因为我想扩展功能,并且想在 Ruby 中执行此操作,而不是从 Ruby 调用 shell 脚本。
我尝试用 Ruby 重写代码,但最终输出存在差异。
shell 代码的输出在 5% 到 10% 之间,而 Ruby 代码的输出在 97.5% 到 97.8% 之间。
这是红宝石代码:
result = `cat /proc/stat | grep '^cpu '`.split(" ")
result.delete("cpu")
idle_time0 = result[4].to_i
total_time0 = 0
result.each do |partial_time|
total_time0 += partial_time.to_i
end
sleep 0.5
result = `cat /proc/stat | grep '^cpu '`.split(" ")
result.delete("cpu")
idle_time = result[4].to_i
total_time = 0
result.each do |partial_time|
total_time += partial_time.to_i
end
diff_idle = idle_time - idle_time0
diff_total = total_time - total_time0
diff_usage = (1000*(diff_total - diff_idle)/(diff_total+5).to_f)/10.0
p diff_usage
这是外壳脚本:
#!/bin/bash
CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
unset CPU[0] # Discard the "cpu" prefix.
IDLE=${CPU[4]} # Get the idle CPU time.
# Calculate the total CPU time.
TOTAL=0
for VALUE in "${CPU[@]}"; do
let "TOTAL=$TOTAL+$VALUE"
done
# Remember the total and idle CPU times for the next check.
PREV_TOTAL="$TOTAL"
PREV_IDLE="$IDLE"
# Wait before checking again.
sleep 0.5
CPU=(`cat /proc/stat | grep '^cpu '`) # Get the total CPU statistics.
unset CPU[0] # Discard the "cpu" prefix.
IDLE=${CPU[4]} # Get the idle CPU time.
# Calculate the total CPU time.
TOTAL=0
for VALUE in "${CPU[@]}"; do
let "TOTAL=$TOTAL+$VALUE"
done
# Calculate the CPU usage since we last checked.
let "DIFF_IDLE=$IDLE-$PREV_IDLE"
let "DIFF_TOTAL=$TOTAL-$PREV_TOTAL"
let "DIFF_USAGE=(1000*($DIFF_TOTAL-$DIFF_IDLE)/$DIFF_TOTAL+5)/10"
echo -en "\rCPU: $DIFF_USAGE% \b\b"