从解释器,我得到:
>>> timeit.repeat("-".join( str(n) for n in range(10000) ) , repeat = 3, number=10000)
[1.2294530868530273, 1.2298660278320312, 1.2300069332122803] # this is seconds
从命令行,我得到:
$ python -m timeit -n 10000 '"-".join(str(n) for n in range(10000))'
10000 loops, best of 3: 1.79 msec per loop # this is milli second
为什么这两种情况下的时间差异如此之大?
最佳答案
这两条线测量的不是同一件事。在第一个片段中,您对计算 0-1-2-...-9999
进行了计时。而在第二个片段中,您正在为字符串连接计时 "-".join(str(n) for n in range(10000))
.
此外,timeit
和repeat
报告总 时间,而 CLI 计算迭代次数的平均时间。所以第一个代码实际上“每个循环”需要 12.29 毫秒。
关于python - 从解释器和命令行使用 timeit 的时间差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19413371/