From a2aa81388c8e22192ba047ddb2637e0f8c632234 Mon Sep 17 00:00:00 2001 From: Stefan Harmuth Date: Sat, 3 Dec 2022 10:06:31 +0100 Subject: [PATCH] better human readable time from ns --- tools/stopwatch.py | 26 ++++---------------------- tools/tools.py | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 22 deletions(-) diff --git a/tools/stopwatch.py b/tools/stopwatch.py index eb059bc..2d0ed6e 100644 --- a/tools/stopwatch.py +++ b/tools/stopwatch.py @@ -1,26 +1,8 @@ from time import perf_counter_ns +from .tools import human_readable_time_from_ns from .types import IntOrNone -def get_time_string_from_ns(ns: int) -> str: - # mis, ns = ns // 1000, ns % 1000 - # ms, mis = mis // 1000, mis % 1000 - # s, ms = ms // 1000, ms % 1000 - # m, s = s // 60, s % 60 - # h, m = m // 60, m % 60 - # d, h = h // 24, h % 24 - - units = ['ns', 'µs', 'ms', 's'] - unit = 0 - while ns > 1_000: - if unit > 3: - break - ns /= 1000 - unit += 1 - - return "%1.2f%s" % (ns, units[unit]) - - class StopWatch: started: IntOrNone = None stopped: IntOrNone = None @@ -39,20 +21,20 @@ class StopWatch: reset = start - def elapsed(self) -> float: + def elapsed(self) -> int: if self.stopped is None: return perf_counter_ns() - self.started else: return self.stopped - self.started def elapsed_string(self) -> str: - return get_time_string_from_ns(self.elapsed()) + return human_readable_time_from_ns(self.elapsed()) def avg_elapsed(self, divider: int) -> float: return self.elapsed() / divider def avg_string(self, divider: int) -> str: - return get_time_string_from_ns(int(self.avg_elapsed(divider))) + return human_readable_time_from_ns(int(self.avg_elapsed(divider))) def __str__(self): return self.avg_string(1) diff --git a/tools/tools.py b/tools/tools.py index 21e5c0f..eec7dcf 100644 --- a/tools/tools.py +++ b/tools/tools.py @@ -64,6 +64,25 @@ def human_readable_time_from_delta(delta: datetime.timedelta) -> str: return time_str + "%02d" % (delta.seconds % 60) +def human_readable_time_from_ns(ns: int) -> str: + units = [ + (1000, 'ns'), + (1000, 'µs'), + (1000, 'ms'), + (60, 's'), + (60, 'm'), + (60, 'h'), + (24, 'd'), + ] + + time_parts = [] + for div, unit in units: + ns, p = ns // div, ns % div + time_parts.insert(0, "%d%s" % (p, unit)) + if ns == 0: + return ", ".join(time_parts) + + def cache(func): saved = {}