Created
July 30, 2020 19:47
-
-
Save umcconnell/c24b276e1f3fdbd1457b2fccba43c80f to your computer and use it in GitHub Desktop.
A simple python decorator to measure function execution time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example usage | |
from time import sleep | |
@timer(repeat=10) | |
def my_function(): | |
sleep(1) | |
return True |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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