Skip to content

Instantly share code, notes, and snippets.

@maurobaraldi
Last active May 7, 2020 21:59
Show Gist options
  • Save maurobaraldi/f55d4441212750b24251fbf975ea665a to your computer and use it in GitHub Desktop.
Save maurobaraldi/f55d4441212750b24251fbf975ea665a to your computer and use it in GitHub Desktop.
Profiler for small pieces of code.
import logging
import time
filename="/tmp/profile.log"
class timer():
def __init__(self, context=""):
'''
Profiler for small pieces of code.
Parameters:
context (string): Name used to identify portion of code profiled.
Result of profile could be found in /tmp/profile.log
'''
logging.basicConfig(level=logging.DEBUG, filename=filename, format="%(asctime)s:%(levelname)s:%(message)s")
self.logger = logging.getLogger(context)
self.logger.info("Starting profile {}".format(context))
self.start = None
self.end = None
def __enter__(self):
self.start = time.time()
self.logger.debug("Start at {}".format(self.start))
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
self.end = time.time()
self.logger.debug("Ending at {}".format(self.end))
self.logger.debug("Elapsed time at {}".format(self.end - self.start))
@maurobaraldi
Copy link
Author

maurobaraldi commented May 7, 2020

Usage

with timer("teste"):
   print('with statement block')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment