Skip to content

Instantly share code, notes, and snippets.

@yangmillstheory
Last active May 20, 2018 17:48
Show Gist options
  • Save yangmillstheory/dfb53c985e39e8b01972dd0d795a531d to your computer and use it in GitHub Desktop.
Save yangmillstheory/dfb53c985e39e8b01972dd0d795a531d to your computer and use it in GitHub Desktop.
Python timer
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