Skip to content

Instantly share code, notes, and snippets.

@umcconnell
Created July 30, 2020 19:47
Show Gist options
  • Save umcconnell/c24b276e1f3fdbd1457b2fccba43c80f to your computer and use it in GitHub Desktop.
Save umcconnell/c24b276e1f3fdbd1457b2fccba43c80f to your computer and use it in GitHub Desktop.
A simple python decorator to measure function execution time
# Example usage
from time import sleep
@timer(repeat=10)
def my_function():
sleep(1)
return True
from time import perf_counter
import functools
def timer(func=None, repeat: int = 1000000):
def _decorate(function):
@functools.wraps(function)
def wrapped_func(*args, **kwargs):
t0 = perf_counter()
for _ in range(repeat):
function(*args, **kwargs)
t1 = perf_counter()
t = 1000 * (t1 - t0)/repeat
print('%s executed in %fms' % (function.__name__, t))
return function(*args, **kwargs)
return wrapped_func
if func:
return _decorate(func)
return _decorate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment