python:慢timeit()函数
当我在 timeit() 之外运行下面的代码时,它似乎立即完成。然而,当我在 timeit() 函数内运行它时,它需要更长的时间。为什么?
>>> import timeit
>>> t = timeit.Timer("3**4**5")
>>> t.timeit()
16.55522028637718
使用: Python 3.1 (x86) - AMD 速龙 64 X2 - WinXP(32 位)
When I run the code below outside of timeit(), it appears to complete instantaneously. However when I run it within the timeit() function, it takes much longer. Why?
>>> import timeit
>>> t = timeit.Timer("3**4**5")
>>> t.timeit()
16.55522028637718
Using:
Python 3.1 (x86) -
AMD Athlon 64 X2 -
WinXP (32 bit)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
timeit() 函数多次运行代码(默认一百万次)并取计时的平均值。
要仅运行代码一次,请执行以下操作:
但这会给您带来偏差的结果 - 它重复是有充分理由的。
要获得让它重复的每个循环时间,请将结果除以循环数。如果一百万太多,请使用较小的重复次数值:
The
timeit()
function runs the code many times (default one million) and takes an average of the timings.To run the code only once, do this:
but that will give you skewed results - it repeats for good reason.
To get the per-loop time having let it repeat, divide the result by the number of loops. Use a smaller value for the number of repeats if one million is too many:
因为 timeit 默认运行一百万次。重点是进行微基准测试,而获得短事件准确计时的唯一方法就是多次重复它们。
Because timeit defaults to running it one million times. The point is to do micro-benchmarks, and the only way to get accurate timings of short events is to repeat them many times.
根据 docs,Timer.timeit() 默认运行您的代码一百万次。使用“number”参数更改此默认值:
例如。
According to the docs, Timer.timeit() runs your code one million times by default. Use the "number" parameter to change this default:
for example.
Timeit 默认运行一百万次循环。
您还可能遇到操作顺序问题:
(3**4)**5 != 3**4**5
。Timeit runs for one million loops by default.
You also may have order of operations issues:
(3**4)**5 != 3**4**5
.