简体   繁体   English

python:慢timeit()函数

[英]python: slow timeit() function

When I run the code below outside of timeit(), it appears to complete instantaneously. 当我在timeit()之外运行下面的代码时,它似乎立即完成。 However when I run it within the timeit() function, it takes much longer. 但是当我在timeit()函数中运行它时,需要更长的时间。 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) 使用:Python 3.1(x86) - AMD Athlon 64 X2 - WinXP(32位)

The timeit() function runs the code many times (default one million) and takes an average of the timings. timeit()函数多次运行代码(默认为100万)并取平均值。

To run the code only once, do this: 要仅运行一次代码,请执行以下操作:

t.timeit(1)

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: 如果一百万个过多,则使用较小的重复次数值:

count = 1000
print t.timeit(count) / count

Because timeit defaults to running it one million times. 因为timeit默认运行它一百万次。 The point is to do micro-benchmarks, and the only way to get accurate timings of short events is to repeat them many times. 重点是做微观基准测试,获得短期事件准确时间的唯一方法是重复多次。

According to the docs , Timer.timeit() runs your code one million times by default. 根据文档 ,Timer.timeit()默认运行您的代码一百万次。 Use the "number" parameter to change this default: 使用“number”参数更改此默认值:

t.timeit(number=100)

for example. 例如。

Timeit runs for one million loops by default. 默认情况下, Timeit运行一百万个循环。

You also may have order of operations issues: (3**4)**5 != 3**4**5 . 您也可能有操作顺序问题: (3**4)**5 != 3**4**5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM