Python中的代码计时块,而不将其放入函数中

Python中的代码计时块,而不将其放入函数中,python,datetime,benchmarking,Python,Datetime,Benchmarking,我希望对代码块计时,而不将其放入单独的函数中。例如: 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)) import time from contextlib import contextmanager @contextmanager def

我希望对代码块计时,而不将其放入单独的函数中。例如:

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))
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)
但是,我希望以更简洁的方式使用timeit模块,但我不想为代码块创建单独的函数


谢谢。

您可以使用
with
语句来完成此操作。例如:

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))
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)
要像这样使用:

def myFunc():
    #...

    with measureTime('myFunc'):
        #block of code to time here

    #...

通过将代码块放在Python的三重引号中,可以设置一个变量来引用要计时的代码块。然后在实例化timeit对象时使用该变量。在某种程度上,我遵循了来自的一个示例,得出了以下结论:

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)
对我来说,这本书是:

499500

0.000341892242432

(其中499500是定时块的输出,0.000341892242432是运行的时间。)

根据这一点,我认为有一个愚蠢的模块可以帮助:



内部函数呢?为什么不把它分离成一个单独的函数呢?因为从设计的角度来看,这是没有意义的——我希望每个做复杂事情的函数都报告自己的计时,但只针对计算密集的块。我不想为了计时+1而扩展函数。如果您在Linux上,想要测量挂钟时间而不是处理器时间,那么您可能需要使用
time.time
而不是
time.clock
。有关详细信息,请参阅。