Skip to content

Commit

Permalink
more timing units.
Browse files Browse the repository at this point in the history
  • Loading branch information
mmcdermott committed Feb 5, 2023
1 parent ca1e711 commit 5fa7f8a
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 4 deletions.
20 changes: 17 additions & 3 deletions mixins/timeable.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ class TimeableMixin():
_END_TIME = 'end'

_CUTOFFS_AND_UNITS = [
(1000, 'μs'),
(1000, 'ms'),
(60, 'sec'),
(60, 'min'),
Expand All @@ -21,11 +22,24 @@ class TimeableMixin():
]

@classmethod
def _get_pprint_num_unit(cls, seconds: float) -> Tuple[float, str]:
ms = seconds * 1000
def _get_pprint_num_unit(cls, x: float, x_unit: str = 'sec') -> Tuple[float, str]:
x_unit_factor = 1
for fac, unit in cls._CUTOFFS_AND_UNITS:
if unit == x_unit: break
if fac is None:
raise LookupError(
f"Passed unit {x_unit} invalid! "
f"Must be one of {', '.join(u for f, u in cls._CUTOFFS_AND_UNITS)}."
)
x_unit_factor *= fac

min_unit = x * x_unit_factor
upper_bound = 1
for upper_bound_factor, unit in cls._CUTOFFS_AND_UNITS:
if upper_bound_factor is None or ms < upper_bound * upper_bound_factor: return ms / upper_bound, unit
if (
(upper_bound_factor is None) or
(min_unit < upper_bound * upper_bound_factor)
): return min_unit / upper_bound, unit
upper_bound *= upper_bound_factor

@classmethod
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "ml_mixins"
version = "0.0.4"
version = "0.0.5"
authors = [
{ name="Matthew B. A. McDermott", email="[email protected]" },
]
Expand Down
14 changes: 14 additions & 0 deletions tests/test_timeable_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,20 @@ def test_responds_to_methods(self):
T._time_so_far('key')
T._register_end('key')

def test_pprint_num_unit(self):
self.assertEqual((5, 'μs'), TimeableMixin._get_pprint_num_unit(5 * 1e-6))

class Derived(TimeableMixin):
_CUTOFFS_AND_UNITS = [
(10, 'foo'),
(2, 'bar'),
(None, 'biz')
]

self.assertEqual((3, 'biz'), Derived._get_pprint_num_unit(3, 'biz'))
self.assertEqual((3, 'foo'), Derived._get_pprint_num_unit(3/20, 'biz'))
self.assertEqual((1.2, 'biz'), Derived._get_pprint_num_unit(2.4 * 10, 'foo'))

def test_context_manager(self):
T = TimeableDerived()

Expand Down

0 comments on commit 5fa7f8a

Please sign in to comment.