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:
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: