2

I'm trying to get the percent of CPU usage for an external process in python. I've seen some other posts on this topic, but haven't helped me too much. When I run the following function I get values that aren't consistent with what I'm seeing in task manager. For example, if I'm monitoring a chrome process I get values that oscillate between 1 and 2, but task manager shows values oscillating between 25 and 30. Any suggestions? Thanks.

def monitor(pid):
    cpu_table = []
    p = psutil.Process(pid)
    while p.is_running():
        cpu_table.append(p.get_cpu_percent())
        time.sleep(1)
    return cpu_table
ChrisD
  • 674
  • 6
  • 15

1 Answers1

2
  1. There are several chrome processes and you might be monitoring the wrong one
  2. cpu_percent() "compares system CPU times elapsed since last call or module import". Pass the same interval that task manager uses (in case, it is not 1 second). Make sure to start both your monitor() function and the task manager at the same time.
Giampaolo RodolĂ 
  • 12,488
  • 6
  • 68
  • 60
jfs
  • 399,953
  • 195
  • 994
  • 1,670