Skip to content

Instantly share code, notes, and snippets.

@moschlar
Created June 2, 2013 12:53
Show Gist options
  • Save moschlar/5693564 to your computer and use it in GitHub Desktop.
Save moschlar/5693564 to your computer and use it in GitHub Desktop.
Python execution timing context manager class
import time
class Timer(object):
def __init__(self, echo=False):
self._start = 0.0
self._stop = 0.0
self.echo = echo
def __enter__(self):
self._start = time.time()
return self
def __exit__(self, type, value, traceback):
self._stop = time.time()
if self.echo:
if isinstance(self.echo, basestring):
print self.echo, self
else:
print self
def __float__(self):
return float(self._stop - self._start)
def __str__(self):
return str(float(self))
__repr__ = __str__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment