在Python psutil中调用函数时,如何监视CPU的使用情况?

2024-09-27 07:26:47 发布

您现在位置:Python中文网/ 问答频道 /正文

嘿,我正在学习psutil软件包,我想知道如何在功能进行时显示当前的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))

Tags: inimport功能fordef情况rangerandom
3条回答

您可以使用multiprocessing库来实现这一点multiprocessing.Process是一个表示线程化进程的类,使用函数和名称启动,并且可以随时使用.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))

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

因为它使用while True,所以线程将永远运行,并且没有好的方法来停止线程,所以我使用全局变量runningwhile 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()

顺便说一句:这可以转换为从类线程继承的类,然后它可以在类中隐藏变量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()

但我跳过这部分

我认为您不需要使用psutilProcess类,因为我认为它是用于监视特定进程的。使用@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

相关问题 更多 >

    热门问题