【发布时间】:2010-10-27 16:59:17
【问题描述】:
我喜欢能够衡量我编写的 Python 函数的性能,所以我经常做类似的事情......
import time
def some_function(arg1, arg2, ..., argN, verbose = True) :
t = time.clock() # works best in Windows
# t = time.time() # apparently works better in Linux
# Function code goes here
t = time.clock() - t
if verbose :
print "some_function executed in",t,"sec."
return return_val
是的,我知道您应该使用 timeit 来衡量性能,但这正好满足我的需求,并且允许我非常顺利地打开和关闭此信息以进行调试。
那段代码当然是在我知道函数装饰器之前......我现在对它们了解不多,但我认为我可以使用 **kwds 字典编写一个执行以下操作的装饰器:
some_function(arg1, arg2, ..., argN) # Does not time function
some_function(arg1, arg2, ..., argN, verbose = True) # Times function
不过,我还是想复制我之前的函数的工作,这样工作就会更像:
some_function(arg1, arg2, ..., argN) # Does not time function
some_function(arg1, arg2, ..., argN, False) # Does not time function
some_function(arg1, arg2, ..., argN, True) # Times function
我想这需要装饰器计算参数的数量,知道原始函数将占用多少,去掉多余的,将正确数量的参数传递给函数......我不确定如何告诉python这样做......有可能吗?有没有更好的方法来达到同样的效果?
【问题讨论】:
标签: python decorator argument-passing