Python Function Timer Decorator
by Jason on March 26, 2012
I find myself often timing how long code blocks take to execute so I’m able to discover bottlenecks and compare performance between iterations.
A quick & simple way to do this is with a handy Python decorator.
import time
import logging as log
def log_timing():
'''Decorator generator that logs the time it takes a function to execute'''
#Decorator generator
def decorator(func_to_decorate):
def wrapper(*args, **kwargs):
start = time.time()
result = func_to_decorate(*args, **kwargs)
elapsed = (time.time() - start)
log.debug("[TIMING]:%s - %s" % (func_to_decorate.__name__, elapsed))
return result
wrapper.__doc__ = func_to_decorate.__doc__
wrapper.__name__ = func_to_decorate.__name__
return wrapper
return decorator
Leave your comment