WMI获取进程CPU占用率

Monitor 

% Process CPU Usage (specific process)
http://www.tek-tips.com/viewthread.cfm?qid=395765
 
for each Process in GetObject("winmgmts:{impersonationLevel=impersonate}//localhost").ExecQuery("Select PercentProcessorTime,IDProcess from Win32_PerfFormattedData_PerfProc_Process where IDProcess=4092")
   
   WScript.Echo("================================")
   For Each oProperty In Process.Properties_
        WScript.stdout.write vbtab & oProperty.Name & "="
        If IsArray(oProperty) Then
            For iCount = 0 To UBound(oProperty)
                WScript.stdout.write  oProperty.Value(iCount) & "," 
            Next
            WScript.StdOut.WriteLine 
        ElseIf IsNull(oProperty) Then
            WScript.stdout.writeline "Property not set"
        Else
            WScript.stdout.writeline oProperty.Value 
        End If 
    Next
    WScript.Echo(Process.PercentProcessorTime)
  WScript.quit  
next
====================================================================================
for each Process in GetObject("winmgmts:").ExecQuery("Select * from Win32_Process")
   WScript.echo Process.name & " " & CPUUSage(Process.Handle) & " %"   
Next

Function CPUUSage( ProcID )
 On Error Resume Next
    
 Set objService = GetObject("Winmgmts:{impersonationlevel=impersonate}!RootCimv2")
    
 For Each objInstance1 in objService.ExecQuery("Select * from Win32_PerfRawData_PerfProc_Process where IDProcess = '" & ProcID & "'")
  N1 = objInstance1.PercentProcessorTime
  D1 = objInstance1.TimeStamp_Sys100NS
  Exit For
 Next
 'WScript.Sleep(2000)
 
 For Each perf_instance2 in objService.ExecQuery("Select * from Win32_PerfRawData_PerfProc_Process where IDProcess = '" & ProcID & "'")
  N2 = perf_instance2.PercentProcessorTime
  D2 = perf_instance2.TimeStamp_Sys100NS
  Exit For
 Next
 ' CounterType - PERF_100NSEC_TIMER_INV
 ' Formula - (1- ((N2 - N1) / (D2 - D1))) x 100
 Nd = (N2 - N1)
 Dd = (D2-D1)
 PercentProcessorTime = ( (Nd/Dd))  * 100
       
 CPUUSage = Round(PercentProcessorTime ,0)
End Function
原文地址:https://www.cnblogs.com/diyunpeng/p/6836150.html