如果你可以牺牲具有numberOfExecTime
参数默认值的能力,你可以这样做:
from timeit import Timer
from functools import partial
def get_execution_time(function, numberOfExecTime, *args, **kwargs):
"""Return the execution time of a function in seconds."""
return round(Timer(partial(function, *args, **kwargs))
.timeit(numberOfExecTime), 5)
def foo(a, b, c = 12):
print a, b, c
get_execution_time(foo, 1, 3, 4, c = 14)
或者你也可以那样做,仍然有默认值numberOfExecTime
:
from timeit import Timer
from functools import partial
def get_execution_time(function, *args, **kwargs):
"""Return the execution time of a function in seconds."""
numberOfExecTime = kwargs.pop('numberOfExecTime', 1)
return round(Timer(partial(function, *args, **kwargs))
.timeit(numberOfExecTime), 5)
def foo(a, b, c = 1):
print a, b, c
get_execution_time(foo, 1, 2, c = 2)
# => 1 2 2
get_execution_time(foo, 4, 5, c = 3, numberOfExecTime = 2)
# => 4 5 3
# => 4 5 3
这是使用现有代码的最佳答案。但是,如果您希望更多地控制您收到的数据,@ KL-7具有更强大的表现力。 – Edwin
我犹豫要发布与KL-7所提议的相同的提案(除了我发布的提案之外),但在我眼中,我最终决定发布的版本是最好的版本,因为此函数的调用更直接,因为没有将哪个传递的参数传递给函数以及哪个是方法本身的参数的歧义... – gecco
这就是为什么我说它具有*更具表现力*。我从来没有说过哪个答案是最好的,因为它取决于提问者想要的东西。 – Edwin