Skip to content

Instantly share code, notes, and snippets.

@mklbtz
Last active October 8, 2018 16:08
Show Gist options
  • Save mklbtz/b6528c7f5c76df58ccb3732a3a7239aa to your computer and use it in GitHub Desktop.
Save mklbtz/b6528c7f5c76df58ccb3732a3a7239aa to your computer and use it in GitHub Desktop.
Stopwatch - A simple class for taking time hacks.
from time import sleep
from .stopwatch import Stopwatch
watch = Stopwatch()
watch.start()
sleep(1)
watch.lap('built query')
sleep(1)
watch.lap('ran query')
sleep(1)
watch.stop('formatted results')
watch.report()
"""
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 = []
@property
def laps(self):
return len(self._hacks) - 1
def start(self, label='start'):
self._add_hack(label)
def stop(self, label='stopped'):
self._add_hack(label)
def lap(self, label=None):
assert self._hacks
self._add_hack(label)
def _add_hack(self, label):
self._hacks.append((datetime.now(), label))
def time(self, lap=None):
if self.laps == -1:
return None
elif self.laps == 0:
return datetime.now() - self._hacks[0][0]
elif lap is None:
return self._hacks[-1][0] - self._hacks[0][0]
else:
return self._hacks[lap + 1][0] - self._hacks[lap][0]
def print_report(self):
print(self.report())
sys.stdout.flush()
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