Created
April 2, 2015 16:33
-
-
Save pmuller/83d1475a2001f277f1af to your computer and use it in GitHub Desktop.
Log timing information (context manager + decorator)
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
import time | |
import logging | |
LOGGER = logging.getLogger(__name__) | |
class DurationLogger(object): | |
"""Log run time duration of an operation. | |
Can be used as a context manager or as a decorator. | |
""" | |
def __init__(self, name, logger=None): | |
self.name = name | |
self.logger = logger or LOGGER | |
self.start_time = None | |
def __call__(self, decorated): | |
"""Make this class usable as a decorator. | |
""" | |
def decorator(*args, **kw): | |
self.start() | |
result = decorated(*args, **kw) | |
self.stop() | |
return result | |
decorator.__doc__ = decorated.__doc__ | |
return decorator | |
def __enter__(self): | |
"""Called when entering the context manager. | |
""" | |
return self.start() | |
def __exit__(self, exc_type, exc_value, traceback): | |
"""Called when exiting the context manager. | |
""" | |
self.stop() | |
def start(self): | |
"""Start the timer. | |
""" | |
self.start_time = time.time() | |
return self.start_time | |
def stop(self): | |
"""Stop the timer and log duration. | |
""" | |
duration = time.time() - self.start_time | |
self.logger.debug('%s: %.4fs' % (self.name, duration)) | |
self.start_time = None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment