timer: pick a single unit based on max duration.

This commit is contained in:
Harmen Stoppels 2022-12-23 09:52:22 -08:00
parent be6bb413df
commit e8fa8c5f01
3 changed files with 25 additions and 17 deletions

View File

@ -741,6 +741,18 @@ def _n_xxx_ago(x):
raise ValueError(msg)
def pretty_seconds_formatter(seconds):
if seconds >= 1:
multiplier, unit = 1, "s"
elif seconds >= 1e-3:
multiplier, unit = 1e3, "ms"
elif seconds >= 1e-6:
multiplier, unit = 1e6, "us"
else:
multiplier, unit = 1e9, "ns"
return lambda s: "%.3f%s" % (multiplier * s, unit)
def pretty_seconds(seconds):
"""Seconds to string with appropriate units
@ -750,15 +762,7 @@ def pretty_seconds(seconds):
Returns:
str: Time string with units
"""
if seconds >= 1:
value, unit = seconds, "s"
elif seconds >= 1e-3:
value, unit = seconds * 1e3, "ms"
elif seconds >= 1e-6:
value, unit = seconds * 1e6, "us"
else:
value, unit = seconds * 1e9, "ns"
return "%.3f%s" % (value, unit)
return pretty_seconds_formatter(seconds)(seconds)
class RequiredAttributeError(ValueError):

View File

@ -120,9 +120,9 @@ def test_timer_write():
output = text_buffer.getvalue().splitlines()
assert "timer" in output[0]
assert "1.0000s" in output[0]
assert "1.000s" in output[0]
assert "total" in output[1]
assert "3.0000s" in output[1]
assert "3.000s" in output[1]
deserialized = json.loads(json_buffer.getvalue())
assert deserialized == {

View File

@ -14,7 +14,7 @@
from collections import OrderedDict, namedtuple
from contextlib import contextmanager
from llnl.util.lang import pretty_seconds
from llnl.util.lang import pretty_seconds_formatter
import spack.util.spack_json as sjson
@ -139,12 +139,16 @@ def write_json(self, out=sys.stdout):
def write_tty(self, out=sys.stdout):
"""Write a human-readable summary of timings"""
# Individual timers ordered by registration
formatted = [(p, f"{self.duration(p):.4f}s") for p in self.phases]
# Total time
formatted.append(("total", f"{self.duration():.4f}s"))
times = [self.duration(p) for p in self.phases]
# Get a consistent unit for the time
pretty_seconds = pretty_seconds_formatter(max(times))
# Tuples of (phase, time) including total.
formatted = list(zip(self.phases, times))
formatted.append(("total", self.duration()))
# Write to out
for name, duration in formatted:
out.write(f" {name:10s} {duration:>10s}\n")
out.write(f" {name:10s} {pretty_seconds(duration):>10s}\n")