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

吃可爱长大的小学妹 提交于 2019-12-05 17:17:19

问题


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.


回答1:


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

    #...



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




回答3:


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)


来源:https://stackoverflow.com/questions/2327719/timing-block-of-code-in-python-without-putting-it-in-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!