From d80a3ae2b1f86f86263d7e5cf6d2b9ec960f62b4 Mon Sep 17 00:00:00 2001 From: Stefan Holst Date: Tue, 28 Feb 2023 09:38:02 +0900 Subject: [PATCH] timer utility --- src/kyupy/__init__.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) 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.