获取cpu使用率并计算使用的%

时间:2012-01-26 17:30:24

标签: linux-kernel cpu-usage

我需要计算cpu使用量并从linux中的proc文件聚合它

/ proc / stat给了我数据,但我怎么会知道cpu的%使用时间 stat为我提供了在任何时间运行的核心进程的计数,这不会让我知道cpu的%使用率? 我正在Golang编写这个,并且必须用脚本

来完成

提前致谢!!

1 个答案:

答案 0 :(得分:1)

/proc/stat不仅可以为您提供每个核心上的进程计数。 man proc会告诉您该文件的确切格式。复制它,这是你应该感兴趣的部分:

   /proc/stat
          cpu  3357 0 4313 1362393
                 The  amount  of  time,  measured  in  units  of   USER_HZ
                 (1/100ths   of   a  second  on  most  architectures,  use
                 sysconf(_SC_CLK_TCK) to obtain the right value), that the
                 system  spent  in  user mode, user mode with low priority
                 (nice), system mode, and  the  idle  task,  respectively.
                 The  last  value should be USER_HZ times the second entry
                 in the uptime pseudo-file.

然后很容易在两个度量之间进行idle字段的减法,这将给你花费时间不用这个CPU做任何事情。您可以提取的另一个值是做某事的时间,这是两个度量之间的差异:

time in user mode + time spent in user mode with low priority + time spent in system mode

然后你会有两个值;一个,A,表达时间无所事事,另一个,B,实际做某事的时间。 B / (A + B)将为您提供CPU忙碌的时间百分比。