I create this working function for getting time of another function:
def get_execution_time(function, args, numberOfExecTime=1):
"""Return the execution time of a function in seconds.
"""
return round(Timer(partial(function, args)).timeit(numberOfExecTime), 5)
By the way I have a problem: I can't give multiple input (args) to the function to be timed. How can I do that? Is partial the right tool?
I tried decorator but I can't store the time which is what I need for doing some statistics.
If you can sacrifice ability to have default value for numberOfExecTime argument you can do it like that:
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)
Or you can do it like that and still have default value for 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With