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.
According with Skilldrick answer there is a silly module that I think can help: BlockLogginInator.
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:
Which for me printed:
(Where 499500 is the output of the timed block, and 0.000341892242432 is the time running.)
You can do this with the
with
statement. For example:To be used like this: