簡體   English   中英

psutil的proc.as_dict屬性“ get_cpu_percent”為每個進程返回0.0

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

我正在嘗試使用psutil模塊編寫一個非常簡單的python腳本,以返回進程ID,創建時間,名稱和CPU%。 最終,我將使用它來基於這些返回值監視特定的閾值,但是對於我們的情況,我將使用一個簡單的示例

  • 作業系統:CentOS 6.5
  • Python:2.6.6(基本CentOS 6軟件包)
  • psutil:0.6.1

當我運行以下腳本時,它將為除cpu_percent之外的所有內容返回正確的值。 每個進程返回0.0。 我認為問題是由於cpu_percent的默認間隔為0。 我正在使用psutil.process_iter()和as_dict遍歷正在運行的進程。 我不確定如何設置間隔。 有什么我想念的嗎?

#! /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)

根據文檔, get_cpu_percent將允許您測量特定進程用作阻塞度量的CPU時間。 例如:

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()

相反,您可能想在報表中使用get_cpu_times

>>> 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM