Instantly share code, notes, and snippets.

Embed
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 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.
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment