Skip to content

Instantly share code, notes, and snippets.

@0asa
Last active December 14, 2018 10:57
Show Gist options
  • Save 0asa/148307674d6eb795eb64440c43bc114e to your computer and use it in GitHub Desktop.
Save 0asa/148307674d6eb795eb64440c43bc114e to your computer and use it in GitHub Desktop.
Timing with python context manager
import time
import logging
class Timer:
def __init__(self, timed, logger=None):
self.logger = logger
self.timed = timed
def __enter__(self):
self.start = time.perf_counter()
return self
def __exit__(self, *args):
self.end = time.perf_counter()
self.interval = self.end - self.start
if self.logger is not None:
if self.interval < 0.01:
self.logger.debug(f"{self.timed}: {self.interval:0.2E} sec.")
else:
self.logger.debug(f"{self.timed}: {self.interval:0.5f} sec.")
# example usage with logging
logging.basicConfig(
handlers=[
logging.StreamHandler(),
# logging.FileHandler("logfile.log", mode='a', encoding='utf8')
],
format='%(asctime)s %(levelname)s [%(module)s]: %(message)s')
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
with Timer("Time", logger=logger) as t:
# something you wanna time
pass
time.sleep(0.5)
# You can also access the time as follow:
print(t.interval)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment