[英]psutil's proc.as_dict attribute “get_cpu_percent” returns 0.0 for each process
我正在嘗試使用psutil模塊編寫一個非常簡單的python腳本,以返回進程ID,創建時間,名稱和CPU%。 最終,我將使用它來基於這些返回值監視特定的閾值,但是對於我們的情況,我將使用一個簡單的示例
當我運行以下腳本時,它將為除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.