time.time vs. timeit.timeit [英] time.time vs. timeit.timeit

查看:63
本文介绍了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.timetime.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 or time.clock in Python 2 and time.perf_counter() on Python 3. See timeit.default_timer.

这篇关于time.time vs. timeit.timeit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆