天天看點

python 計算windows上的某個程序的cpu使用率

import time
import wmi
 
wmiInterface = wmi.WMI ()
 
process_info = {}
while True: #Change the looping condition
  for process in wmiInterface.Win32_Process (name="NAME of the EXE"):
    id = process.ProcessID
    for p in wmiInterface.Win32_PerfRawData_PerfProc_Process (IDProcess=id):
      n1, d1 = long (p.PercentProcessorTime), long (p.Timestamp_Sys100NS)
      n0, d0 = process_info.get (id, (0, 0))
      try:
        percent_processor_time = (float (n1 - n0) / float (d1 - d0)) *100.0
      except ZeroDivisionError:
        percent_processor_time = 0.0
      process_info[id] = (n1, d1)
      print id, process.Caption, str(percent_processor_time)
           

說明:

1. 多少時間計算一次cpu使用率,需要自行考慮。上述例子隻是示範如何計算cpu使用率。

2. 計算出來的cpu使用率是一個cpu的使用率。如果是2核,則最高cpu使用率為200%。