如果您可以牺牲为参数设置默认值的能力,则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