py-tools/tools/stopwatch.py

52 lines
1.2 KiB
Python

from time import perf_counter_ns
from .types import IntOrNone
def ns_to_string(ns: int) -> str:
units = ['ns', 'µs', 'ms', 's']
unit = 0
while ns > 1_000:
ns /= 1_000
unit += 1
if unit == len(units) - 1:
break
return f"{ns:1.2f}{units[unit]}"
class StopWatch:
started: IntOrNone = None
stopped: IntOrNone = None
def __init__(self, auto_start=True):
if auto_start:
self.start()
def start(self):
self.started = perf_counter_ns()
self.stopped = None
def stop(self) -> int:
self.stopped = perf_counter_ns()
return self.elapsed()
reset = start
def elapsed(self) -> int:
if self.stopped is None:
return perf_counter_ns() - self.started
else:
return self.stopped - self.started
def avg_elapsed(self, divider: int) -> int:
return self.elapsed() // divider # in ns precision loosing some rounding error probably will not hurt
def elapsed_string(self):
return ns_to_string(self.elapsed())
def avg_string(self, divider: int) -> str:
return ns_to_string(self.avg_elapsed(divider))
def __str__(self):
return self.avg_string(1)