[英]Python psutil module using too much cpu when iterating through processes on Windows
我一直在嘗試創建一個監視器來了解哪個進程使用 cpu 最多以及總體 cpu 使用情況我需要它每秒刷新一次信息,為此我一直在使用 psutil 但是當我使用下一塊Windows 上的代碼它使用了我的 CPU 的 8%,而在 Linux 上它幾乎沒有使用我認為 8% 太多了,Window 的任務管理器甚至不使用 2%,它顯示了很多信息,有什么我可以做的怎么做才能降低cpu使用率?
import time
import psutil
while True:
ini_proc_cpu_usage = [] # Stores initial cpu usage per process
last_proc_cpu_usage = [] # Stores last cpu usage per process
process_name = [] # Processes name
process_index = 0 # Keeps track of index to remove non-existent processes
# Creates new list with all the current running processes
procs = [process for process in psutil.process_iter()]
# First request to get overall cpu usage
psutil.cpu_percent(0)
# First request to get cpu usage per process
for p in procs[:]:
# Condition for windows platform to ignore
# System Idle Process from processes
if not p.name() == "System Idle Process":
try:
# Appends cpu usage per process
ini_proc_cpu_usage.append(p.cpu_percent(0))
# Exception if the process doesn't exist anymore
except (psutil.NoSuchProcess, psutil.ZombieProcess):
procs.remove(p) # Removes process from list
continue
# Exception for access denied due to user privileges
except psutil.AccessDenied:
procs.remove(p)
pass
time.sleep(1) # Time nedeed tu get more accurate info
# Second request to get overall cpu usage
last_cpu_usage = psutil.cpu_percent(0)
# Second request to get top io process info
for p in procs[:]:
# Condition for windows platform to ignore
# System Idle Process from processes
if not p.name() == "System Idle Process":
try:
# Oneshot makes info request quicker
with p.oneshot():
# Creates list with io information for the second time
last_proc_cpu_usage.append(p.cpu_percent(0))
process_name.append(p.name()) # Gets process name
process_index += 1 # Counter for getting index
# Exception if the process doesn't exist anymore
except (psutil.NoSuchProcess, psutil.ZombieProcess):
procs.remove(p) # Removes process from list
# Removes process from ini_proc_cpu_usage as well
ini_proc_cpu_usage.pop(process_index)
continue
# Exception for access denied due to user privileges
except psutil.AccessDenied:
procs.remove(p)
pass
# Gets cpu usage in percentage
cpu_percent = str(round(last_cpu_usage))
# Gets top process index this is useful to get process name
top_process_index = last_proc_cpu_usage.index(max(last_proc_cpu_usage))
# Converts average top cpu usage into percent
top_cpu_percent = max(last_proc_cpu_usage)
top_cpu_percent = top_cpu_percent / psutil.cpu_count()
top_cpu_percent = f"{top_cpu_percent:.1f}"
# Gets process name
top_process_name = process_name[top_process_index]
print(f"{cpu_percent}%, {top_process_name}: {top_cpu_percent}%")
萬一其他人遇到這個問題,我發現只是通過運行腳本作為管理員解決了它,現在 psutil 幾乎不使用我的 cpu。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.