Skip to content

Commit

Permalink
Add formatting based on the timeit CLI interface
Browse files Browse the repository at this point in the history
  • Loading branch information
yut23 committed Apr 24, 2024
1 parent 5fe480c commit 69ab9a3
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/yut23_utils/timing.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ def _format_time(
class TimingFormat(enum.Enum):
IPYTHON = enum.auto()
HYPERFINE = enum.auto()
TIMEIT = enum.auto()


@dataclass(frozen=True)
Expand Down Expand Up @@ -113,6 +114,11 @@ def time_str(timespan: float) -> str:
f" (mean ± std. dev. of {label_count(self.repeat, 'loop')},"
f" {loop_str} each)"
)
if fmt is TimingFormat.TIMEIT:
return (
f"{loop_str}, best of {self.repeat}:"
f" {_format_time(self.min)} per loop"
)
raise AssertionError


Expand Down
22 changes: 22 additions & 0 deletions tests/test_timing.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,25 @@ def test_pretty_ipython_single(self):
assert info.pretty(TimingFormat.IPYTHON) == (
"3.14 s ± nan s per loop (mean ± std. dev. of 1 loop, 2 loops each)"
)

def test_pretty_timeit(self):
times = (1.23, 3.21, 2.75, 2.53)

info = TimingInfo(times, 1)
assert info.pretty(TimingFormat.TIMEIT) == "1 loop, best of 4: 1.23 s per loop"

info = TimingInfo(times, 3)
assert info.pretty(TimingFormat.TIMEIT) == "3 loops, best of 4: 1.23 s per loop"

def test_pretty_timeit_single(self):
times = (3.14159,)

info = TimingInfo(times, 1)
assert info.pretty(TimingFormat.TIMEIT) == (
"1 loop, best of 1: 3.14 s per loop"
)

info = TimingInfo(times, 2)
assert info.pretty(TimingFormat.TIMEIT) == (
"2 loops, best of 1: 3.14 s per loop"
)

0 comments on commit 69ab9a3

Please sign in to comment.