Skip to content

Instantly share code, notes, and snippets.

@sujeetkv
Last active September 4, 2023 20:53
Show Gist options
  • Save sujeetkv/675e82c0b9f0c2c094b56d7b884347ea to your computer and use it in GitHub Desktop.
Save sujeetkv/675e82c0b9f0c2c094b56d7b884347ea to your computer and use it in GitHub Desktop.
Python context manager cum decorator to log execution time
import logging
from time import perf_counter
from contextlib import ContextDecorator
class timedlog(ContextDecorator):
def __init__(self, msg='Elapsed time', logger=None):
self.msg = msg
self.logger = logger or logging.getLogger(__name__)
def __enter__(self):
self.start_time = perf_counter()
return self
def __exit__(self, *args):
self.end_time = perf_counter()
self.elapsed_time = self.end_time - self.start_time
self.logger.warning('%s: %.3fs', self.msg, self.elapsed_time)
return False
# as decorator
@timedlog()
def myf():
# do stuff
# as context manager
with timedlog():
# do stuff
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment