Skip to content

Instantly share code, notes, and snippets.

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.

This comment has been minimized.

Copy link

markusdr commented Nov 14, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.