Skip to content

Instantly share code, notes, and snippets.

Last active October 8, 2018 16:08
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Stopwatch - A simple class for taking time hacks.
from time import sleep
from .stopwatch import Stopwatch
watch = Stopwatch()
watch.lap('built query')
watch.lap('ran query')
watch.stop('formatted results')
1) 1.0s - built query
2) 1.0s - ran query
3) 1.0s - formatted results
3.0s - Total Time
from datetime import datetime, timedelta
import sys
class Stopwatch:
def __init__(self):
self._hacks = []
def laps(self):
return len(self._hacks) - 1
def start(self, label='start'):
def stop(self, label='stopped'):
def lap(self, label=None):
assert self._hacks
def _add_hack(self, label):
self._hacks.append((, label))
def time(self, lap=None):
if self.laps == -1:
return None
elif self.laps == 0:
return - self._hacks[0][0]
elif lap is None:
return self._hacks[-1][0] - self._hacks[0][0]
return self._hacks[lap + 1][0] - self._hacks[lap][0]
def print_report(self):
def report(self):
def delta(previous, current):
ptime = self._hacks[previous][0]
ctime, label = self._hacks[current]
return (ctime - ptime, label)
def format_delta(delta, label):
return "{:6.1f}s - {}".format(delta.total_seconds(), label)
def generate_report():
hacks = len(self._hacks)
padlen = len(str(hacks))
format_index = lambda idx: str(idx).zfill(padlen) + ') '
for i, j in zip(xrange(hacks), xrange(1, hacks)):
yield format_index(j) + format_delta(*delta(i, j))
summary = ' ' * len(format_index(0)) + format_delta(self.time(), 'Total Time')
yield '-' * len(summary)
yield summary
return "\n".join(generate_report())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment