Skip to content

Instantly share code, notes, and snippets.

@jonathan-kosgei
Last active June 14, 2021 05:01
Show Gist options
  • Save jonathan-kosgei/a0e3fb78d81f9f3a09778ced6eca7161 to your computer and use it in GitHub Desktop.
Save jonathan-kosgei/a0e3fb78d81f9f3a09778ced6eca7161 to your computer and use it in GitHub Desktop.
Python Decorator to Time a Function
""" 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.
#
@markusdr
Copy link

This works for me only when I change line 10 from
return new_function()
to
return new_function

@livinlefevreloca
Copy link

As written it will call the decorated function on import.

@tairun
Copy link

tairun commented Dec 6, 2019

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:

  1. Use the @wraps(new_function) decorator from functools (from functools import wraps) between line 4 and 5.
  2. 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