Created
October 21, 2021 20:05
-
-
Save luizhenriquefbb/e479a1c31330b0e75a78721f583641ab to your computer and use it in GitHub Desktop.
A decorator that prints how long a function took
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
# see gist of LogManager (https://gist.github.com/luizhenriquefbb/040124818a5c56ffba81d91929801be5) | |
def timeit(logger:LogManager=None): | |
def decorator(function): | |
def wrapper(*args, **kwargs): | |
ts = time.time() | |
result = function(*args, **kwargs) | |
te = time.time() | |
log_string = f'func:{function.__name__} args:[{args}, {kwargs}] took: {"{:.2f}".format(te-ts)} sec' | |
if logger: | |
logger.debug(log_string) | |
else: | |
print(log_string) | |
return result | |
return wrapper | |
return decorator | |
# usage: | |
# logger = LogManager(log_name="test", folder=os.path.join(BASE_PATH, "logs")) | |
# @timeit(logger=logger) | |
# def test_func(): | |
# sleep(1) | |
# return "ok" | |
# test_func() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment