cpu百分比linux,Linux:cpu使用百分比的计算
處理器時間由分離的時間片(ticks)組成。在一些時間片上,cpu繁忙;另一些時間片上,cpu空閑。下圖表示,在10個時間片上其中6個是繁忙的,cpu使用百分比是6/10 = 60%,也即是40%的空閑時間。
注意:一個cpu周期是單個脈沖時間,脈沖由高低電壓組成。每秒中有上億個ticks,取決于cpu的頻率。
你可以從/proc/stat中獲得自計算機啟動后的CPU ticks個數:
$ cat /proc/stat
user nice? system? idle?? iowait? irq? softirq steal guest guest_nice
cpu? 1732 182??? 590??? 4682??? 1022??? 0????? 34???? 0??? 0????? 0
計算公式
自計算機啟動后總的CPU時間:
@1 = user+nice+system+idle+iowait+irq+softirq+steal
自計算機啟動后總的CPU空閑時間:
@2 = idle + iowait
自計算機啟動后CPU繁忙的時間:
@3 = @1 - @2
總的cpu使用百分比:
@3 / @1 X 100
注意 Guest 和 Guest_nice已經計算到了 user 和 nice中。
為了獲得實時的cpu使用百分比,你需要計算時間間隔的ticks數。
實時計算cpu使用百分比的的bash腳本(Paul Colby編寫):
#!/bin/bash
# by Paul Colby (http://colby.id.au), no rights reserved ;)
PREV_TOTAL=0
PREV_IDLE=0
while true; do
# Get the total CPU statistics, discarding the 'cpu ' prefix.
CPU=(`sed -n 's/^cpu\s//p' /proc/stat`)
IDLE=${CPU[3]} # Just 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"
# Remember the total and idle CPU times for the next check.
PREV_TOTAL="$TOTAL"
PREV_IDLE="$IDLE"
# Wait before checking again.
sleep 1
done
總結
以上是生活随笔為你收集整理的cpu百分比linux,Linux:cpu使用百分比的计算的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: cd 地址 linux,Ubuntu10
- 下一篇: vs 构建linux 项目,使用Linu