简体   繁体   中英

psutil's proc.as_dict attribute “get_cpu_percent” returns 0.0 for each process

I am trying to write a very simple python script using the psutil module to return process ID, Create time, Name and CPU %. Ultimately I will use this to monitor specific thresholds based on these returned values, but for our case, I'll use a simple example

  • OS: CentOS 6.5
  • Python: 2.6.6 (base CentOS 6 package)
  • psutil: 0.6.1

When I run the following script, it returns the correct values for everything but cpu_percent. It returns 0.0 for each process. I think the problem is due to the default interval being 0 for cpu_percent. I'm using psutil.process_iter() and as_dict to iterate through the running processes. I'm not sure how I would set the interval. Is there something I'm missing?

#! /usr/bin/python
import psutil

for proc in psutil.process_iter():
    try:
        pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time', 'get_cpu_percent'])
    except psutil.NoSuchProcess:
        pass
    else:
        print(pinfo)

According to the docs, get_cpu_percent will allow you to measure the amount of CPU time a particular process is using as a blocking measurement. For example:

import psutil
import os

# Measure the active process in a blocking method,
#    blocks for 1 second to measure the CPU usage of the process
print psutil.Process(os.getpid()).get_cpu_percent(interval=1)
# Measure the percentage of change since the last blocking measurement.
print psutil.Process(os.getpid()).get_cpu_percent()

Instead, you probably want to use get_cpu_times in your report.

>>> help(proc.get_cpu_times)
Help on method get_cpu_times in module psutil:

get_cpu_times(self) method of psutil.Process instance
    Return a tuple whose values are process CPU user and system
    times. The same as os.times() but per-process.

>>> pinfo = psutil.Process(os.getpid()).as_dict(attrs=['pid', 'name', 'create_time', 'get_cpu_times'])
>>> print (pinfo.get('cpu_times').user, pinfo.get('cpu_times').system)
(0.155494768, 0.179424288)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM