timing block of code in Python without putting it

2019-04-04 17:47发布

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.

3条回答
等我变得足够好
2楼-- · 2019-04-04 18:19

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)
查看更多
萌系小妹纸
3楼-- · 2019-04-04 18:31

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

查看更多
看我几分像从前
4楼-- · 2019-04-04 18:40

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

    #...
查看更多
登录 后发表回答