13

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.

2
  • How about an inner function? What is the reason behind not separating this out into a separate function? Commented Feb 24, 2010 at 16:44
  • 1
    Because from a design perspective it doesn't make sense -- I want each function that does something complicated to report its own timing, but only for the block that is computationally intense. I dont want to proliferate functions for the purpose of timing Commented Feb 24, 2010 at 16:51

3 Answers 3

28

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

    #...
Sign up to request clarification or add additional context in comments.

1 Comment

+1. If you're on Linux and want to measure wall clock time instead of processor time, you'll probably want to use time.time instead of time.clock. See the Python library documentation for details.
2

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.)

Comments

0

According with Skilldrick answer there is a silly module that I think can help: BlockLogginInator.

import time
from blocklogginginator import logblock  # logblock is the alias

with logblock(name='one second'):
    """"
    Our code block.
    """
    time.sleep(1)

>>> Block "one second" started 
>>> Block "one second" ended (1.001)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.