Skip to content

Instantly share code, notes, and snippets.

@AO8
Created October 9, 2018 16:12
Show Gist options
  • Select an option

  • Save AO8/b44e190486ed037f8b17156c154f36be to your computer and use it in GitHub Desktop.

Select an option

Save AO8/b44e190486ed037f8b17156c154f36be to your computer and use it in GitHub Desktop.
Handy Python stopwatch recipe for recording the time it takes to perform a task.
# Stopwatch recipe taken from Python Cookbook, 3rd Edition, by David Beazley and Brian K. Jones.
# Page 561: "As a general rule of thumb, the accuracy of timing measurements made with functions
# such as time.time() or time.clock() varies according to the operation system. In contast,
# time.perf_counter() always uses the highest-resolution timer available on the system."
import time
class Timer:
def __init__(self, func=time.perf_counter):
self.elapsed = 0.0
self._func = func
self._start = None
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
@property
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