Get CPU usage of a single process in Windows

Tim Golden tim.golden at viacom-outdoor.co.uk
Tue Sep 12 08:15:03 EDT 2006


[Gerrit Muller]

| If you have a working example of CPU usage could you post the 
| result? I would be interested.

OK. Here's a workingish example, cut down from the link
I posted earlier. This one was designed to work with Win2K
which I was using at the time. For WinXP and later, there's
a new counter with the ungainly name of 

Win32_PerfFormattedData_PerfProc_Process

which should give you the number straight off without having
to do the take-and-diff-and-divide dance. However, it doesn't
seem to do anything useful on my (XP) system. Haven't tried
that hard, I admit.

As ever, if you can find any example around the Web -- and there
are loads -- converting it to Python should be a breeze.

TJG

<code>
import time
import wmi

c = wmi.WMI ()

process_info = {}
while True:
  for process in c.Win32_Process ():
    id = process.ProcessID
    for p in c.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)
      
      if percent_processor_time > 0.01:
        print "%20s - %2.3f" % (process.Caption, percent_processor_time)

  print
  time.sleep (5)

</code>

________________________________________________________________________
This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk
________________________________________________________________________



More information about the Python-list mailing list