Reputation: 307
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)
Upvotes: 19
Views: 9332
Reputation: 8876
Timeit runs for one million loops by default.
You also may have order of operations issues: (3**4)**5 != 3**4**5
.
Upvotes: 2
Reputation: 1607
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.
Upvotes: 4
Reputation: 375834
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.
Upvotes: 6
Reputation: 281755
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
Upvotes: 33