Skip to content

Instantly share code, notes, and snippets.

Last active June 14, 2021 05:01
What would you like to do?
Python Decorator to Time a Function
""" A simple decorator that times the duration of a function's execution. More info on Decorators at"""
import timeit
def timer(function):
def new_function():
start_time = timeit.default_timer()
elapsed = timeit.default_timer() - start_time
print('Function "{name}" took {time} seconds to complete.'.format(name=function.__name__, time=elapsed))
return new_function()
def addition():
total = 0
for i in range(0,1000000):
total += i
return total
# Function "addition" took 0.081396356006735 seconds to complete.
Copy link

tairun commented Dec 6, 2019

This works for me only when I change line 10 from
return new_function()
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:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment