time.perf_counter() 或 time.process_time() 用于性能测量?

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

我知道 time.perf_counter() 会测量经过的总时间,即使进程当前未运行。然而 time.process_time() 只测量进程实际运行的时间。

如果我只是衡量一个功能的性能,这两个中哪一个是首选?

由于我实际上对 CPU 花在处理其他进程上的时间并不感兴趣,所以我自然认为 time.process_time() 会是更好的选择(并且在不同的运行中更稳定?),但名称 time.perf_counter() 似乎提出其他建议。

代码示例

import time
from tqdm import trange

start_time_proc = time.process_time()
start_time_perf = time.perf_counter()

tmp = False
for _ in trange(10_000_000):
    tmp = not tmp

elapsed_time_proc = time.process_time() - start_time_proc
elapsed_time_perf = time.perf_counter() - start_time_perf

print("process_time:", elapsed_time_proc)
print("perf_counter:", elapsed_time_perf)

https://repl.it/repls/GigaSpryScientists#main.py

python
1个回答
4
投票

通常的测量方法是使用性能计数器并重复测量几次。

处理时间并不经常使用,我可以很容易地向您展示原因:

time.sleep(1)
根据处理时间将花费 0 秒。每次从调度程序中删除进程时,即使是由于正在测试的代码,进程时钟也不会提前。

我可以建议您看一下内置的

timeit
模块吗?它也使用性能计数器,并且可以为重复计时提供更方便的接口。

编辑

当且仅当您的函数完全受 CPU 限制,不访问外部资源,也不引起任何系统调用,

process_time
是更准确、更好的选择。

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