开发者

timing block of code in Python without putting it in a function

开发者 https://www.devze.com 2022-12-21 16:06 出处:网络
I\'d lik开发者_开发技巧e to time a block of code without putting it in a separate function. for example:

I'd lik开发者_开发技巧e 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.


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

    #...


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号