WinBatch Tech Support Home

Database Search

If you can't find the information using the categories below, post a question over in our WinBatch Tech Support Forum.

TechHome

User Sample Code

Can't find the information you are looking for here? Then leave a message over on our WinBatch Tech Support Forum.

Get CPU Usage of a Process


objLocator = ObjectCreate("WbemScripting.SWbemLocator")
objService = objLocator.ConnectServer(".","root/cimv2","","")
objSecurity = objService.Security_
objSecurity.ImpersonationLevel = 3
query = "SELECT * FROM Win32_PerfRawData_PerfProc_Process WHERE Name = 'notepad'"
;query = "SELECT * FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess = '1234'"


; query instances
ForEach objInstance1 In objService.ExecQuery(query)
    N1 = objInstance1.PercentProcessorTime
    D1 = objInstance1.TimeStamp_Sys100NS
    Break
Next


TimeDelay(2)
; query instances
ForEach perf_instance2 In objService.ExecQuery( query )
   N2 = perf_instance2.PercentProcessorTime
   D2 = perf_instance2.TimeStamp_Sys100NS
   Break
Next

; CounterType - PERF_100NSEC_TIMER_INV
; Formula - (1- ((N2 - N1) / (D2 - D1))) x 100
Nd = N2 - N1
Dd = D2 - D1
PercentProcessorTime = ( (Nd/Dd))  * 100

Pause('PercentProcessorTime', PercentProcessorTime)
Exit
Notes: This a nice example of a situation where WMI efficiently wraps up a Win32 API function call that would otherwise have to been done w/DllCall() and some binary buffer manipulation. The Win32 API function in question is GetProcessTimes(), and it takes a process handle as input and requires 4 pointers to 64-bit integers as outputs.

Now, one possible caveat to consider as a difference between how things are working w/WMI and how things are working if you do it using DllCall()... and the caveat is this:

With WMI, each time you use this method, you are going to have to find the process of interest and get the CPU utilization times for it. This will be done at some timed interval, and it is possible that between polling intervals that the process will terminate after having used some additional amount of CPU time since the previous polling interval. If knowing the exact amount of consumed CPU time at process termination time is mandatory, or if the polling interval is sufficiently long, this could be a problem. To keep the terminated process around in a semi-zombie state, you would need to open a handle to it so that it couldn't be deleted after termination, which should then allow WMI to report on its final CPU consumption values, and would definitely allow GetProcessTimes() to do so. The Process extender could be used in conjunction w/WMI to open a handle to the process for this purpose.


Article ID:   W17504
File Created: 2011:02:08:10:33:48
Last Updated: 2011:02:08:10:33:48