py-tools/tools/stopwatch.py
2021-12-27 16:29:46 +01:00

36 lines
807 B
Python

from time import time
from .types import FloatOrNone
class StopWatch:
started: FloatOrNone = None
stopped: FloatOrNone = None
def __init__(self, auto_start=True):
if auto_start:
self.start()
def start(self):
self.started = time()
self.stopped = None
def stop(self) -> float:
self.stopped = time()
return self.elapsed()
def elapsed(self) -> float:
if self.stopped is None:
return time() - self.started
else:
return self.stopped - self.started
def __str__(self):
units = ['s', 'ms', 'µs', 'ns']
unit = 0
elapsed = self.elapsed()
while elapsed < 1:
elapsed *= 1000
unit += 1
return "%1.2f%s" % (elapsed, units[unit])