Skip to content

Instantly share code, notes, and snippets.

@omri374
Created May 16, 2020 17:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omri374/2219f793e660ca8247d1525c9be134f6 to your computer and use it in GitHub Desktop.
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
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