Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 265
HC. Avatar asked Aug 10 '09 23:08

HC.


People also ask

What is the Timeit function in Python?

Source code: Lib/timeit.py. This module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times.

Does Timeit return seconds or milliseconds?

The return value is seconds as a float. It is the total time taken to run the test (not counting the setup), so the average time per test is that number divided by the number argument, which defaults to 1 million.

Is Timeit Python in seconds?

The Python timeit() method accepts the code as a string and returns the execution time in seconds. On the contrary, the default_timer() method returns the time of its execution. The repeat() method calls the timeit() method a number of specified times.

What does the Timeit function return?

The timeit() method returns the amount of time it takes to execute the statement repeatedly. The output of show_results() converts that into the amount of time it takes per iteration, and then further reduces the value to the average amount of time it takes to store one item in the dictionary.


2 Answers

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
like image 131
RichieHindle Avatar answered Oct 07 '22 10:10

RichieHindle


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.

like image 20
Ned Batchelder Avatar answered Oct 07 '22 10:10

Ned Batchelder