Python中的代码时序块,无需将其放入函数中

12 python benchmarking datetime

我想计算一段代码而不将它放在一个单独的函数中.例如:

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))
Run Code Online (Sandbox Code Playgroud)

但是,我想以更干净的方式使用timeit模块执行此操作,但我不想为代码块创建单独的函数.

谢谢.

int*_*jay 26

您可以使用该with语句执行此操作.例如:

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)
Run Code Online (Sandbox Code Playgroud)

要像这样使用:

def myFunc():
    #...

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

    #...
Run Code Online (Sandbox Code Playgroud)