views:

91

answers:

2

I'd like to time a block of code without putting it in a separate function. for example:

def myfunc:
  # some code here
  t1 = time.time()
  # block of code to time here
  t2 = time.time()
  print "Code took %s seconds." %(str(t2-t1))

however, I'd like to do this with the timeit module in a cleaner way, but I don't want to make a separate function for the block of code.

thanks.

+5  A: 

You can do this with the with statement. For example:

import time    
from contextlib import contextmanager

@contextmanager  
def measureTime(title):
    t1 = time.clock()
    yield
    t2 = time.clock()
    print '%s: %0.2f seconds elapsed' % (title, t2-t1)

To be used like this:

def myFunc():
    #...

    with measureTime('myFunc'):
        #block of code to time here

    #...
interjay
+2  A: 

You can set up a variable to refer to the code block you want to time by putting that block inside Python's triple quotes. Then use that variable when instantiating your timeit object. Somewhat following an example from the Python timeit docs, I came up with the following:

import timeit
code_block = """\
total = 0
for cnt in range(0, 1000):
    total += cnt
print total
"""
tmr = timeit.Timer(stmt=code_block)
print tmr.timeit(number=1)

Which for me printed:

499500

0.000341892242432

(Where 499500 is the output of the timed block, and 0.000341892242432 is the time running.)

GreenMatt