为什么 psutil 有时会报告 0.0% CPU 使用率?

问题描述 投票:0回答:1

我正在尝试使用 psutil python 库来测量当前进程随时间的 CPU 利用率 (

os.getpid()
)。该脚本旨在打印每 1 秒间隔内的 CPU 使用率值。模拟的平均负载旨在相当低(~1%),与我将测量的真实过程类似。

问题是 psutil 似乎有时会报告 0.0% 使用率的值,这在 1 秒的间隔内没有意义(请注意模拟加载函数中的 0.1 秒睡眠时间)。有人可以帮助我理解 psutil 报告的值或指出我是否以某种方式滥用它。

谢谢!

版本

python=3.10.8 psutil = 5.9.0

import time
import random
import psutil
import threading

test_time = 10
start_time = time.perf_counter()

def simulate_load():
    while time.perf_counter() - start_time < test_time:
        c = 0
        for _ in range(350):
            c += random.randint(0, 5)
        time.sleep(0.1)

def measure_load():
    log = []
    this_process = psutil.Process()
    this_process.cpu_affinity([15])
    this_process.cpu_percent(interval=0)
    while time.perf_counter() - start_time < test_time:
       log.append(this_process.cpu_percent(interval=0))
       time.sleep(1)
    return log

background_thread = threading.Thread(target=simulate_load)
background_thread.start()

print(measure_load())

输出

[0.0, 1.6, 1.5, 0.0, 1.6, 1.5, 0.0, 0.0, 0.0, 3.1]

python cpu-usage psutil
1个回答
0
投票

range(350)
太低了,您无法在现代计算机上注意到某些内容。 例如尝试使用
range(1e6)

对于 350,我得到:[0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0]

对于 1e6:[186.3, 81.1, 80.1, 89.4, 89.4, 90.4, 79.5, 80.5, 78.5, 82.6]

有趣的数字和数量级参考表

© www.soinside.com 2019 - 2024. All rights reserved.