time.perf_counter()或time.process_time()用于性能评估?

时间:2020-09-06 00:58:50

标签: python

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

1 个答案:

答案 0 :(得分:2)

通常的测量方法是使用性能计数器,然后重复测量两次。

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

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