您好,登錄后才能下訂單哦!
小編給大家分享一下Python如何實現(xiàn)統(tǒng)計本機CPU利用率,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
模塊win32pdh是Python中的一個模塊,封裝了Windows Performance Data Helpers API。
win32pdh方法
AddCounter 添加一個新計數(shù)器
AddEnglishCounter 通過英文名稱為查詢添加計數(shù)器
RemoveCounter 刪除一個打開的計數(shù)器。
EnumObjectItems 枚舉對象的項目
EnumObjects 枚舉對象
OPENQUERY 打開一個新查詢
CloseQuery 關(guān)閉打開的查詢。
MakeCounterPath 制作完全解決的計數(shù)器路徑
GetCounterInfo 檢索有關(guān)計數(shù)器的信息,例如數(shù)據(jù)大小,計數(shù)器類型,路徑和用戶提供的數(shù)據(jù)值。
GetFormattedCounterValue 檢索格式化的計數(shù)器值
CollectQueryData 收集指定查詢中所有計數(shù)器的當前原始數(shù)據(jù)值,并更新每個計數(shù)器的狀態(tài)代碼。
ValidatePath 驗證指定的計數(shù)器是否存在于計數(shù)器路徑中指定的計算機上。
ExpandCounterPath 檢查指定的計算機(如果沒有指定本地計算機),則檢查與計數(shù)器路徑中的通配符字符串匹配的計數(shù)器和計數(shù)器實例。
ParseCounterPath 解析計數(shù)器路徑的元素。
ParseInstanceName 解析實例名稱的元素
SetCounterScaleFactor 設(shè)置在請求格式化計數(shù)器值時應(yīng)用于指定計數(shù)器的計算值的比例因子。
BrowseCounters 顯示計數(shù)器瀏覽對話框,以便用戶可以選擇要返回給調(diào)用者的計數(shù)器。
ConnectMachine 連接到指定的計算機,并在PDH DLL中創(chuàng)建和初始化計算機條目。
LookupPerfIndexByName 返回與指定計數(shù)器名稱對應(yīng)的計數(shù)器索引。
LookupPerfNameByIndex 返回與指定索引對應(yīng)的性能對象名稱。
完整代碼:python統(tǒng)計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 "在統(tǒng)計的1分鐘內(nèi),cpu已經(jīng)有5次大于4%" listcpu=[] print y
看完了這篇文章,相信你對Python如何實現(xiàn)統(tǒng)計本機CPU利用率有了一定的了解,想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。