Created
October 14, 2010 15:22
-
-
Save hntrmrrs/626357 to your computer and use it in GitHub Desktop.
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 TimedOperation(object): | |
| "Describes a single operation with timing information" | |
| __slots__ = ('description', '_cpustart', '_cpuend', '_wallstart', '_wallend') | |
| def __init__(self, description): | |
| self.description = description | |
| self._cpustart = time.clock() | |
| self._cpuend = None | |
| self._wallstart = time.time() | |
| self._wallend = None | |
| def __repr__(self): | |
| return u'<TimedOperation %s %.3f CPU seconds %.3f wall seconds>' % ( | |
| self.description, self.cpu_duration, self.wall_duration) | |
| __str__ = __repr__ | |
| __unicode__ = __str__ | |
| @property | |
| def cpu_duration(self): | |
| "Duration of the event" | |
| if self._cpuend is None: | |
| raise Exception("Not finished") | |
| return self._cpuend - self._cpustart | |
| @property | |
| def wall_duration(self): | |
| "Duration of the event" | |
| if self._wallend is None: | |
| raise Exception("Not finished") | |
| return self._wallend - self._wallstart | |
| def finish(self): | |
| "Complete the timing" | |
| if self._cpuend is not None: | |
| raise Exception("Already finished") | |
| self._cpuend = time.clock() | |
| self._wallend = time.time() | |
| @classmethod | |
| @contextlib.contextmanager | |
| def timed(cls, description, tlist=None): | |
| operation = cls(description) | |
| yield operation | |
| operation.finish() | |
| if tlist is not None: | |
| tlist.append(operation) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment