Last active
June 14, 2021 05:01
-
-
Save jonathan-kosgei/a0e3fb78d81f9f3a09778ced6eca7161 to your computer and use it in GitHub Desktop.
Python Decorator to Time a Function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" A simple decorator that times the duration of a function's execution. More info on Decorators at https://pythonconquerstheuniverse.wordpress.com/2009/08/06/introduction-to-python-decorators-part-1/""" | |
import timeit | |
def timer(function): | |
def new_function(): | |
start_time = timeit.default_timer() | |
function() | |
elapsed = timeit.default_timer() - start_time | |
print('Function "{name}" took {time} seconds to complete.'.format(name=function.__name__, time=elapsed)) | |
return new_function() | |
@timer | |
def addition(): | |
total = 0 | |
for i in range(0,1000000): | |
total += i | |
return total | |
# | |
# Function "addition" took 0.081396356006735 seconds to complete. | |
# |
As written it will call the decorated function on import.
This works for me only when I change line 10 from
return new_function()
to
return new_function
Yes, very true. Also this code can be improved in two ways:
- Use the
@wraps(new_function)
decorator from functools (from functools import wraps
) between line 4 and 5. - With this solution, the decorated function cannot have any arguments. Here is a better implementation: https://stackoverflow.com/a/51503837
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works for me only when I change line 10 from
return new_function()
to
return new_function