module timeit and variable scope

brianc at temple.edu brianc at temple.edu
Mon Aug 2 16:30:44 EDT 2004


>1. What are the advantages of using timeit compared to using
>time.time() or time.clock()? (on Mac OS X)
It's more accurate when timing very small bits of code. Though
I don't know a thing about Max OS X.

>2. How do I introduce a variable into the timeit.Timer? For
example I
>have a class Foo:
Just create an instance in the setup portion of the Timer.
t=timeit.Timer('foo.run()','from __main__ import Foo; foo=Foo()')
To just test __init__ of your class:
t=timeit.Timer('Foo()','from __main__ import Foo')

Setup only runs once.

-Brian

---- Original message ----
>Date: 2 Aug 2004 10:40:24 -0700
>From: fortepianissimo at gmail.com (fortepianissimo)  
>Subject: module timeit and variable scope  
>To: python-list at python.org
>
>A couple questions about using timeit to record the CPU time
consumed
>by an instance method:
>
>
>2. How do I introduce a variable into the timeit.Timer? For
example I
>have a class Foo:
>
>class Foo:
>  def __init__ (self):
>    # the following line didn't work because the scope is not
>    #   the calling function
>    # self._timer = timeit.Timer(stmt='self.run(bar)')
>    pass
>
>  def someMethod (self, bar):
>    print bar
>
>  def run (self, bar):
>    # call self.someMethod(bar) and record time using
>    #   self._timer
>    pass
>
>
>and I want to record the CPU time consumed by someMethod in
method
>run(), using the timer initialized in __init__(). The reason
to set up
>the timer in __init__ is to avoid overhead of setting up the same
>timer time and time again in run().
>
>Thank you.
>-- 
>http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list