cpu百分比linux,Linux:cpu使用百分比的计算

处理器时间由分离的时间片(ticks)组成。在一些时间片上,cpu繁忙;另一些时间片上,cpu空闲。下图表示,在10个时间片上其中6个是繁忙的,cpu使用百分比是6/10 = 60%,也即是40%的空闲时间。

de9725a48434eccc221f2d802ee4510a.png

注意:一个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

42f9072885183a2c978d264cc58b4618.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值