简体   繁体   中英

python: slow timeit() function

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)

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:

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. 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. Use the "number" parameter to change this default:

t.timeit(number=100)

for example.

Timeit runs for one million loops by default.

You also may have order of operations issues: (3**4)**5 != 3**4**5 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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