Python中的代码的定时块,而不会放在一个函数中 [英] timing block of code in Python without putting it in a function
本文介绍了Python中的代码的定时块,而不会放在一个函数中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想把一段代码放在一个单独的函数中。例如:
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))
但是,我想用timeit模块在一个更干净的方式,但我不想为代码块单独的功能。
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.
谢谢。
推荐答案
您可以使用与
语句一起执行此操作。例如:
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)
要像这样使用:
def myFunc():
#...
with measureTime('myFunc'):
#block of code to time here
#...
这篇关于Python中的代码的定时块,而不会放在一个函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文