Created
May 16, 2020 17:20
-
-
Save omri374/2219f793e660ca8247d1525c9be134f6 to your computer and use it in GitHub Desktop.
Time took context manager. This class logs the time it took for a code chunk to run, using a context manager wrapper
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 time | |
class TimeTook(object): | |
""" | |
Calculates the time a block took to run. | |
Example usage: | |
with TimeTook("sample"): | |
s = [x for x in range(10000000)] | |
Modified from: https://blog.usejournal.com/how-to-create-your-own-timing-context-manager-in-python-a0e944b48cf8 | |
""" | |
def __init__(self, description): | |
self.description = description | |
def __enter__(self): | |
self.start = time() | |
def __exit__(self, type, value, traceback): | |
self.end = time() | |
logging.info(f"Time took for {self.description}: {self.end - self.start}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment