[Python-Dev] timeit module

Connelly Barnes connellybarnes at yahoo.com
Mon Jan 16 06:27:23 CET 2006


Perhaps I am the only one bothered by the timeit
module, but it seems poorly designed to me.

First of all, it should use a geometric series with a
timeout value to detect how many iterations it should
perform.  Currently, the user is required to manually
specify the number of iterations (the default is 1
million).  If the user optimizes his or her code, then
the number of iterations must be changed.  If the user
moves to a slower or faster computer, then the number
of iterations must be changed again.  This is

Secondly, there should be a way to time a callable
directly.  That is, without finding the string name of
the callable and using a string "import X" statement. 
These contortions violate rules #1 and #3 of the Zen
of Python.

Yes, there is function call overhead in timing a
callable as opposed to a fragment of code.  However,
when I'm benchmarking code I am often timing
functions, so it seems logical to make this easy to

I have three (mutually exclusive) ideas for improving
the current situation:

 * Add a time_callable() or time_func() function to
   the timeit module.  These would take the callable,
   args, kwargs, and maximum time* to spend timing the
   function as arguments.
 * Add a FuncTimer class (function/callable timer) to
   existing timeit module.  The constructor takes a
   args, kwargs as arguments.  The class has instance
   timeit(max_time=4.0) and repeat(repeat=3,
 * Create a new timeit module (e.g. timeit2) which
   geometric series to implement both code fragment
   (which timeit does) and callable timing.

I have a simple implementation of geometric series
timing routines for callables and code fragments. 
This is recipe


This recipe leaves the GC enabled.

Clearly, this is simple to implement.  If python-dev
likes the
idea of improving Python's timeit functionality, I
volunteer to
implement whichever interface is decided upon.


Connelly Barnes

* The maximum time will be exceeded only if a single
call to
  the callable takes more than max_time seconds.

Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 

More information about the Python-Dev mailing list