module timeit and variable scope

fortepianissimo fortepianissimo at gmail.com
Mon Aug 2 19:40:24 CEST 2004


A couple questions about using timeit to record the CPU time consumed
by an instance method:

1. What are the advantages of using timeit compared to using
time.time() or time.clock()? (on Mac OS X)

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.



More information about the Python-list mailing list