繁体   English   中英

在 Python psutil 中调用 function 时如何监控 CPU 使用率?

[英]How to monitor usage of CPU when function is called in Python psutil?

嘿,我正在学习 psutil package,我想知道当 function 正在进行时如何显示当前的 CPU 使用率? 我想我需要一些线程或类似的东西,但是怎么做呢? 谢谢你的任何答案。

import psutil
import random

def iHateThis():
    tab = []
    for i in range(100000):
        tab.append(random.randint(1, 10000))

    tab.sort()
    return tab;

while(True):
    currentProcess = psutil.Process()
    print(currentProcess.cpu_percent(interval=1))

您可以使用threading来运行iHateThis或使用cpu_percent()运行 function。 我选择第二个版本。 我将在线程中运行cpu_percent()

因为它使用while True所以线程将永远运行并且不会有很好的方法来停止线程所以我使用全局变量running while running有方法来停止这个循环。

import threading
import psutil

def display_cpu():
    global running

    running = True

    currentProcess = psutil.Process()

    # start loop
    while running:
        print(currentProcess.cpu_percent(interval=1))

def start():
    global t

    # create thread and start it
    t = threading.Thread(target=display_cpu)
    t.start()

def stop():
    global running
    global t

    # use `running` to stop loop in thread so thread will end
    running = False

    # wait for thread's end
    t.join()

现在我可以使用它来启动和停止将显示 CPU 的线程。 因为我可能必须使用Ctrl+C停止进程,所以它会引发错误,所以我使用try/finally来停止线程,即使会有错误。

def i_hate_this():
    tab = []
    for i in range(1000000):
        tab.append(random.randint(1, 10000))
    tab.sort()
    return tab

# ---

start()
try:
    result = i_hate_this()
finally: # stop thread even if I press Ctrl+C
    stop()

完整代码:

import random
import threading
import psutil

def display_cpu():
    global running

    running = True

    currentProcess = psutil.Process()

    # start loop
    while running:
        print(currentProcess.cpu_percent(interval=1))

def start():
    global t

    # create thread and start it
    t = threading.Thread(target=display_cpu)
    t.start()

def stop():
    global running
    global t

    # use `running` to stop loop in thread so thread will end
    running = False

    # wait for thread's end
    t.join()

# ---

def i_hate_this():
    tab = []
    for i in range(1000000):
        tab.append(random.randint(1, 10000))
    tab.sort()
    return tab

# ---

start()
try:
    result = i_hate_this()
finally: # stop thread even if I press Ctrl+C
    stop()

顺便说一句:这可以转换为 class 继承自 class 线程,然后它可以隐藏在 class 中running的变量。

import psutil
import random
import threading

class DisplayCPU(threading.Thread):

    def run(self):

        self.running = True

        currentProcess = psutil.Process()

        while self.running:
            print(currentProcess.cpu_percent(interval=1))

    def stop(self):
        self.running = False

# ----

def i_hate_this():
    tab = []
    for i in range(1000000):
        tab.append(random.randint(1, 10000))
    tab.sort()
    return tab

# ---

display_cpu = DisplayCPU()

display_cpu.start()
try:
    result = i_hate_this()
finally: # stop thread even when I press Ctrl+C
    display_cpu.stop()

它也可以转换为上下文管理器来运行它

with display_cpu():
    i_hate_this()

但我跳过这部分。

您可以使用multiprocessing库来做到这一点。 multiprocessing.Process是一个 class 代表一个线程进程,使用 function 和名称启动,并且可以随时使用.start()运行。

import multiprocessing
import psutil
import random

def iHateThis():
    tab = []
    for i in range(100000):
        tab.append(random.randint(1, 10000))
    tab.sort()
    return tab;

hate = multiprocessing.Process(name='hate', target=iHateThis)
hate.start()

while(True):
    currentProcess = psutil.Process()
    print(currentProcess.cpu_percent(interval=1))

我认为您不需要使用 psutil Process class ,因为我认为它旨在用于监视特定进程。 使用来自@furas 的代码片段(接受的答案),您可以使用这样的线程来执行此操作:

def run(self):
    self.run = True 
    while self.run:
        psutil.cpu_percent(interval=1)

在以下情况下,它与接受的答案相同:

    _monitor.start()
    try:
        for i in range(50):
            time.sleep(0.2)
    finally:    
        _monitor.stop()

如果您不想对其进行编码,如果它对某人有任何帮助,我将在公共回购中进行: https://github.com/GTimothee/monitor

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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