time.time vs. timeit.timeit [英] time.time vs. timeit.timeit
问题描述
有时,我喜欢计算我的部分代码运行所需的时间.我已经检查了很多在线站点,并且大致上看到了两种主要的方法来做到这一点.一种是使用 time.time
,另一种是使用 timeit.timeit
.
Sometimes, I like to time how long it takes parts of my code to run. I've checked a lot of online sites and have seen, at large, two main ways to do this. One is using time.time
and the other is using timeit.timeit
.
所以,我写了一个非常简单的脚本来比较两者:
So, I wrote a very simple script to compare the two:
from timeit import timeit
from time import time
start = time()
for i in range(100): print('ABC')
print(time()-start, timeit("for i in range(100): print('ABC')", number=1))
基本上,它乘以在 for 循环中打印 "ABC" 100 次所需的时间.左边的数字是 time.time
的结果,右边的数字是 timeit.timeit
的结果:
Basically, it times how long it takes to print "ABC" 100 times in a for-loop. The number on the left is the results for time.time
and the number on the right is for timeit.timeit
:
# First run
0.0 0.012654680972022981
# Second run
0.031000137329101562 0.012747430190149865
# Another run
0.0 0.011262325239660349
# Another run
0.016000032424926758 0.012740166697164025
# Another run
0.016000032424926758 0.0440628627381413
如您所见,有时 time.time 更快,有时更慢.哪种方法更好(更准确)?
As you can see, sometimes, time.time is faster and sometimes it's slower. Which is the better way (more accurate)?
推荐答案
timeit
更准确,原因有以下三个:
timeit
is more accurate, for three reasons:
- 它会多次重复测试以消除其他任务对您机器的影响,例如磁盘刷新和操作系统调度.
- 它通过在不合时宜的时刻安排收集运行来禁用垃圾收集器,以防止该进程歪曲结果.
- 它为您的操作系统选择最准确的计时器,
time.time
或time.clock
在 Python 2 和time.perf_counter()
在 Python 3 上.参见timeit.default_timer
.
- it repeats the tests many times to eliminate the influence of other tasks on your machine, such as disk flushing and OS scheduling.
- it disables the garbage collector to prevent that process from skewing the results by scheduling a collection run at an inopportune moment.
- it picks the most accurate timer for your OS,
time.time
ortime.clock
in Python 2 andtime.perf_counter()
on Python 3. Seetimeit.default_timer
.
这篇关于time.time vs. timeit.timeit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!