timeit

Michele Simionato mis6 at pitt.edu
Mon Jun 16 09:00:14 EDT 2003


"Bryan" <belred1 at yahoo.com> wrote in message news:<8a2Ha.209222$M01.92818 at sccrnsc02>...
> i tried timeit for the first time today, pretty darn impressive.  i've
> noticed that postings in this newsgroup use timeit on the command line and
> with usually just one simple statement or loop.  is this the only way to use
> timeit?  can timeit be used within a script?  or to execute whole scripts? i
> guess the obvious anwer that one is:
> 
> timeit -s"import myscript" "myscript.main()"
> 
> i'm just curious how other are exploiting timeit.
> 
> thanks,
> 
> bryan

I have added timeit to the module containing my personal utility functions:

  #<util.py>

  import timeit,__main__,warnings

  warnings.filterwarnings('ignore',
  'import \* only allowed at module level',SyntaxWarning)

  def timeit_(stmt,setup='from __main__ import *',n=1000):
      t=timeit.Timer(stmt,setup)
      try: print t.repeat(number=n)
      except: t.print_exc()

  #</util.py>

Here is an example of usage (to measure the function call overhead):

>>> from util import timeit_
>>> def f(): pass
...
>>> timeit_('f()',n=1000000)
[1.9124521017074585, 1.9128650426864624, 1.9139430522918701]

More or less 2 seconds for a million of calls.

HTH,

       Michele




More information about the Python-list mailing list