Last active
May 20, 2018 17:48
-
-
Save yangmillstheory/dfb53c985e39e8b01972dd0d795a531d to your computer and use it in GitHub Desktop.
Python timer
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, func=None): | |
if func is None: | |
func = time.perf_counter | |
self._func = func | |
self.reset() | |
def start(self): | |
if self._start is not None: | |
raise RuntimeError('Already started') | |
self._start = self._func() | |
def stop(self): | |
if self._start is None: | |
raise RuntimeError('Not started') | |
end = self._func() | |
self.elapsed += end - self._start | |
self._start = None | |
def reset(self): | |
self.elapsed = 0.0 | |
self._start = None | |
@proper | |
def running(self): | |
return self._start is not None | |
def __enter__(self): | |
self.start() | |
return self | |
def __exit__(self, *args): | |
self.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment