本文实例讲述了python统计cpu利用率的方法。分享给大家供大家参考。具体实现方法如下:
#-*-coding=utf-8-*-
import win32pdh
import time
# counter paths
processor_percent = r’\processor(_total)\% processor time’
memory_percent = r’\memory\% committed bytes in use’
memory_committed = r’\memory\committed bytes’
process_bytes = lambda x: r’\process(%s)\private bytes’ % x
class query:
def __init__(self):
self.counters = {}
self.query = none
self.query = win32pdh.openquery(none, 0)
def add_counter(self, path):
if win32pdh.validatepath(path) != 0:
raise exception(‘invalid path: %s’ % path)
counter = win32pdh.addcounter(self.query, path, 0)
self.counters[path] = counter
def remove_counter(self, path):
win32pdh.removecounter(self.counters[path])
del self.counters[path]
def get_values(self):
values = {}
win32pdh.collectquerydata(self.query)
for path in self.counters:
status, value = win32pdh.getformattedcountervalue(
self.counters[path], win32pdh.pdh_fmt_long)
values[path] = value
return values
sysinfo_query = query()
sysinfo_query.add_counter(processor_percent)
sysinfo_query.add_counter(memory_percent)
sysinfo_query.get_values()
def get_sysinfo():
“””return a tuple (mem_usage, cpu_usage).”””
info = sysinfo_query.get_values()
return info[memory_percent], info[processor_percent]
listcpu=[]
while true:
time.sleep(2)
x,y=get_sysinfo()
listcpu.append(y)
if len(listcpu)==10:
icount=0
for c in listcpu:
if c>4:
icount+=1
if icount>5:
print “在统计的1分钟内,cpu已经有5次大于4%”
listcpu=[]
print y
希望本文所述对大家的python程序设计有所帮助。