Skip to content

Instantly share code, notes, and snippets.

@micaleel
Last active October 19, 2018 16:15
Show Gist options
  • Select an option

  • Save micaleel/5e124ec295a3d299b3b4b5c94e86e684 to your computer and use it in GitHub Desktop.

Select an option

Save micaleel/5e124ec295a3d299b3b4b5c94e86e684 to your computer and use it in GitHub Desktop.
Poor man's stopwatch profiler for code blocks
import time
import datetime
class Stopwatch:
def __init__(self, message: None, silent=False, callback=None):
self._start = None
self._stop = None
self._silent = silent
self._message = message
self._callback = callback
def print_message(self, message):
if not self._silent:
if self._callback:
self._callback(message)
else:
print('Duration: {}'.format(message))
def start(self):
self._start = datetime.datetime.now()
self.print_message(self._message)
def stop(self):
self._stop = datetime.datetime.now()
@property
def duration(self):
return self._stop - self._start
def __enter__(self):
self.start()
return self
def __exit__(self, *args):
self.stop()
self.print_message(self.duration)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment