After coming across this excellent explanation about decorators, I realized decorators can be quite useful to display function execution times. My ultimate goal is to create a function
compare_functions(f1, f2)
that compares the execution times of two functions f1 and f2. As a start I designed this decorator:
def clean_exec_time(fnc):
def wrapper(*args):
t0 = time.perf_counter()
fnc(*args)
t1 = time.perf_counter()
print(t1-t0)
return wrapper
Which can be used perfectly in this way:
@clean_exec_time
def print_msg(msg):
print(msg)
Such that
print_msg('Hi')
# outputs:
# Hi
# 3.0109e-05
That's great. It get's tricky (for me) when I try to work my way to the ultimate goal.
@clean_exec_time
def compare_functions(f1, f2):
a = 2 #not sure what to put here
Now I see the following:
compare_functions(print_msg('Hi'), print_msg('See ya'))
# outputs
# Hi
# 3.0793e-05
# See ya
# 1.1291e-05
# 6.5010e-05
I have a few questions:
- Why are 2 execution times printed after 'See ya'?
- What do I need to modify in order to see a value c printed that denotes the number of times f1 is faster/slower than f2.
- It feels strange not to put anything meaningful in my function compare_functions. Is there an elegant way to cope with this?