首页 > 解决方案 > time.perf_counter() 或 time.process_time() 用于性能测量?

问题描述

我知道 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

解决方案


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

处理时间不经常使用,我可以很容易地向您展示原因:time.sleep(1)根据处理时间将花费 0 秒。每次从调度程序中删除进程时,即使是由于正在测试的代码,进程时钟也不会提前。

我可以建议您看一下内置的 timeit 模块吗?它也使用 perf counter,并且可以为重复计时提供更舒适的界面。

编辑

当且仅当您的函数完全受 CPU 限制,不访问外部资源,也不引起任何系统调用,process_time才是更准确和更好的选择。


推荐阅读