Skip to content

Instantly share code, notes, and snippets.



Last active Aug 29, 2015
What would you like to do?
TimingLogger context manager
import datetime
import logging
class TimingLogger(object):
Simple timer context manager to log the time spent in the context
to given logger (logging api).
Usage example:
with TimingLogger(title="Compile"):
# Do compile stuff here
# Result: start, end and elapsed time will be logged (to root logger in this case)
def __init__(self, logger=None, title="Timer"):
self._logger = logger or logging.getLogger()
self._title = title
def __enter__(self):
self.start_time = datetime.datetime.utcnow()'{title} start time: {time}'.format(title=self._title, time=self.start_time))
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.end_time = datetime.datetime.utcnow()
self.elapsed = self.end_time - self.start_time'{title} end time: {time}, elapsed: {elapsed}'.format(title=self._title, time=self.end_time, elapsed=self.elapsed))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.