Last active
October 11, 2019 22:46
-
-
Save JoaoCarabetta/fe0fea0f6320231926e58035cd702f49 to your computer and use it in GitHub Desktop.
Get execution time of any part of your code with this context manager for python
This file contains hidden or 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
import logging | |
from contextlib import contextmanager | |
log = logging.getLogger(__name__) | |
@contextmanager | |
def timed_log(name, time_chunk='seconds'): | |
"""Context manager to get execution time of parts of codes. | |
To use, simply declares the context manager: | |
```with timed_log(name='useful', time_chunck='minutes'): | |
-- your code to get execution time here | |
``` | |
Do not forget to set your logging lib to print INFO logs. | |
Parameters | |
---------- | |
name : str | |
a useful name for you to know which part of the code you are measuring | |
time_chunck : str, optional | |
can be `minutes` or `seconds`, by default 'seconds' | |
""" | |
printlog = lambda name, t, time_chunk: log.info(' '.join(map(str, [name, 'took', t, time_chunk]))) | |
start_time = time.time() | |
try: | |
yield start_time | |
finally: | |
total_time = time.time() - start_time | |
if time_chunk == 'seconds': | |
printlog(name, round(total_time, 1), time_chunk) | |
elif time_chunk == 'minutes': | |
printlog(name, round(total_time / 60, 2), time_chunk) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment