python: slow timeit() function

9k views Asked by At

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)

4

There are 4 answers

6
RichieHindle On BEST ANSWER

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
0
Ned Batchelder On

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.

0
Jeff Bradberry On

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.

1
A B On

Timeit runs for one million loops by default.

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