Last active
May 7, 2020 21:59
-
-
Save maurobaraldi/f55d4441212750b24251fbf975ea665a to your computer and use it in GitHub Desktop.
Profiler for small pieces of code.
This file contains hidden or 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 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)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage