diff --git a/src/kyupy/__init__.py b/src/kyupy/__init__.py index 042c555..fd6ab26 100644 --- a/src/kyupy/__init__.py +++ b/src/kyupy/__init__.py @@ -6,6 +6,7 @@ if they are available and otherwise point to mocks. """ import time +from collections import defaultdict import importlib.util import gzip @@ -74,6 +75,24 @@ def hr_time(seconds): return s +class Timer: + def __init__(self): self.s = 0 + def __enter__(self): self.start_time = time.perf_counter() + def __exit__(self, *args): self.s += time.perf_counter() - self.start_time + @property + def ms(self): return self.s*1e3 + @property + def us(self): return self.s*1e6 + def __repr__(self): return f'{self.s:.3f}s' if self.s >= 1 else f'{self.ms:.3f}ms' + + +class Timers: + def __init__(self): self.timers = defaultdict(Timer) + def __getitem__(self, name): return self.timers[name] + def __getattr__(self, name): return self.timers[name] + def __repr__(self): return ''.join([f'{k}={v} ' for k, v in self.timers.items()]) + + class Log: """A very simple logger that formats the messages with the number of seconds since program start.