我想计算一段代码,而不是将它放在一个单独的函数中。例如:
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))
但是,我想以更干净的方式使用timeit模块执行此操作,但我不想为代码块创建单独的函数。
感谢。
答案 0 :(得分: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)
要像这样使用:
def myFunc():
#...
with measureTime('myFunc'):
#block of code to time here
#...
答案 1 :(得分:2)
您可以通过将该块放在Python的三引号中来设置变量以引用您想要计时的代码块。然后在实例化timeit对象时使用该变量。有点跟随Python timeit docs的一个例子,我想出了以下内容:
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是运行的时间。)
答案 2 :(得分:0)
根据Skilldrick answer,我认为有一个愚蠢的模块可以提供帮助: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)