Linux:cpu使用百分比的计算

admin

admin

发表于 2016-07-14 16:39:46

处理器时间由分离的时间片(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/^cpus//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%  bb"

# Remember the total and idle CPU times for the next check.
PREV_TOTAL="$TOTAL"
PREV_IDLE="$IDLE"

# Wait before checking again.
sleep 1
done



用户评论(0)
大牛,别默默的看了,快登录帮我点评一下吧 :)      登录 | 注册

×
×
51前端

注册

×
绑定手机

请绑定手机号,在继续操作

×
单次下载支付

应付金额:279

支付完成后,回到下载页面,在进行下载

官方QQ群
意见反馈
qq群

扫描上面二维码加微信群

官方QQ群

jQuery/js讨论群
群号:642649996
Css3+Html5讨论群
群号:322131262

加群请备注:从官网了解到