Created
June 2, 2013 12:53
-
-
Save moschlar/5693564 to your computer and use it in GitHub Desktop.
Python execution timing context manager class
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 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