月度归档:五月 2013

通过/proc/stat文件信息,java实现计算cpu使用率

/proc/stat 文件内容:
[root@Shentar ~]# cat /proc/stat
cpu 602 0 2164 11445 2294 0 17 0 0
cpu0 306 0 1232 4553 2125 0 15 0 0
cpu1 295 0 932 6891 169 0 1 0 0
intr 7110 269 7 0 1 1 0 5 0 1 0 0 0 91 0 0 106 0 6521 0 108 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 38984
btime 1368275792
processes 2713
procs_running 1
procs_blocked 0
[root@Shentar ~]#

第一行的数值表示的是CPU总的使用情况,所以我们只要用第一行的数字计算就可以了。下表解析第一行各数值的含义:

参数 解析(单位:jiffies)

(jiffies是内核中的一个全局变量,用来记录自系统启动一来产生的节拍数,在linux中,一个节拍大致可理解为操作系统进程调度的最小时间片,不同linux内核可能值有不同,通常在1ms到10ms之间)

user (38082) 从系统启动开始累计到当前时刻,处于用户态的运行时间,不包含 nice值为负进程。

nice (627) 从系统启动开始累计到当前时刻,nice值为负的进程所占用的CPU时间

system (27594) 从系统启动开始累计到当前时刻,处于核心态的运行时间

idle (893908) 从系统启动开始累计到当前时刻,除IO等待时间以外的其它等待时间iowait (12256) 从系统启动开始累计到当前时刻,IO等待时间(since 2.5.41)

irq (581) 从系统启动开始累计到当前时刻,硬中断时间(since 2.6.0-test4)

softirq (895) 从系统启动开始累计到当前时刻,软中断时间(since 2.6.0-test4)stealstolen(0) which is the time spent in other operating systems when running in a virtualized environment(since 2.6.11)

guest(0) which is the time spent running a virtual CPU for guest operating systems under the control of the Linux kernel(since 2.6.24)

结论:总的cpu时间totalCpuTime = user + nice + system + idle + iowait + irq + softirq + stealstolen + guest

计算时,采样两个时间点的数据,对于时间点1,记录总的cpu时间total1,记录空闲时间idle1,对于时间2,同样记录total2和idle2。

菜谱使用率为:cpuusage = 1 – (idle2 – idle1) / (total2 – total1)

注意,如果时间点1和时间点2间隔足够小(小于10ms),则可能出现total2 – total1为0,这样cpu使用率应该为0,而不是采用除法计算。

java代码如下:

阅读全文 »

| 1 分2 分3 分4 分5 分 (5.00- 3票) Loading ... Loading ... | 归档目录:Java |
返回顶部