【问题标题】:Obtain %cpu usage: is this script correct?获取 %cpu 使用率:这个脚本是否正确?
【发布时间】:2014-03-15 19:59:11
【问题描述】:

我发现这个 python 脚本似乎可以完成这项工作,但我不知道它是否真的正确,我无法解释自己最后几行的 100-。

其背后的理论很清楚:将 CPU 花费的用户、系统和 i/o 时间相加,然后除以相同的总和加上空闲时间。这将为您提供 % 的 cpu 负载。

我不需要 100% 准确的测量,只需要一些关于实际 %cpu 使用率的提示。

import time

TIMEFORMAT = "%m/%d/%y %H:%M:%S"
INTERVAL = 2

def getTimeList():
   statFile = file("/proc/stat", "r")
   timeList = statFile.readline().split(" ")[2:6]
   statFile.close()
   for i in range(len(timeList))  :
     timeList[i] = int(timeList[i])

   return timeList

def deltaTime(interval)  :
   x = getTimeList()
   time.sleep(interval)
   y = getTimeList()
   for i in range(len(x))  :
      y[i] -= x[i]
   return y

if __name__ == "__main__"  :
   while True  :
      dt = deltaTime(INTERVAL)
      timeStamp = time.strftime(TIMEFORMAT)
      cpuPct = 100 - (dt[len(dt) - 1] * 100.00 / sum(dt)) #why 100 - ?
      print timeStamp + "\t" + str('%.4f' %cpuPct) 

【问题讨论】:

    标签: python linux monitoring


    【解决方案1】:

    100 是 100%。表达式产生时间空闲,你想要时间忙。从 100 中减去。

    【讨论】:

      猜你喜欢
      • 2014-03-29
      • 2010-09-08
      • 2016-08-17
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多