I find the following piece of re-usable code handy when testing functions.
import timeit
def timed_function(f, *args, **kwargs):
myname = str(f).split(' ')[1]
def new_func(*args, **kwargs):
timer1 = timeit.default_timer()
result = f(*args, **kwargs)
timer2 = timeit.default_timer()
delta = timer2 - timer1
print('Function {} Time = {:6.3f}ms'.format(myname, delta*1000))
return result
return new_func
You can use it to decorate any function and then it will print the original function's name and execution time every time you run it.
Something like this:
@timed_function
def func1():
return sum([0.5 for i in range(10000)])
y = func1()
Code output:
Function func1 Time = 0.849ms
[I got the idea from here.]