获取%cpu使用率:此脚本是否正确?

2024-09-30 02:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我找到了这个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) 

Tags: inforlenreturntimedef时间dt

热门问题