8000 Add the ability to compare a timer to another value. (#13) · realpython/codetiming@d618696 · GitHub
[go: up one dir, main page]

Skip to content

Commit d618696

Browse files
janfreyberggahjelle
authored andcommitted
Add the ability to compare a timer to another value. (#13)
* Add the ability to compare a timer to another value. This allows checking whether the last measured time is greater or less than some 'reference' value. This is useful if you want to display messages if some operation has taken too long in the past. * Use `last` for previous measurement - also removes comparators, as timer.last can be used for comparison * fix import sorting in tests * sort imports in timer file * relax the assertion of measured time in test
1 parent 496709a commit d618696

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

codetiming/_timer.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
"""
66

77
# Standard library imports
8+
import time
89
from contextlib import ContextDecorator
910
from dataclasses import dataclass, field
10-
import time
11+
from math import nan
1112
from typing import Any, Callable, ClassVar, Dict, Optional
1213

1314

@@ -24,6 +25,7 @@ class Timer(ContextDecorator):
2425
text: str = "Elapsed time: {:0.4f} seconds"
2526
logger: Optional[Callable[[str], None]] = print
2627
_start_time: Optional[float] = field(default=None, init=False, repr=False)
28+
last: float = field(default=nan, init=False, repr=False)
2729

2830
def __post_init__(self) -> None:
2931
"""Initialization: add timer to dict of timers"""
@@ -43,16 +45,16 @@ def stop(self) -> float:
4345
raise TimerError(f"Timer is not running. Use .start() to start it")
4446

4547
# Calculate elapsed time
46-
elapsed_time = time.perf_counter() - self._start_time
48+
self.last = time.perf_counter() - self._start_time
4749
self._start_time = None
4850

4951
# Report elapsed time
5052
if self.logger:
51-
self.logger(self.text.format(elapsed_time))
53+
self.logger(self.text.format(self.last))
5254
if self.name:
53-
self.timers[self.name] += elapsed_time
55+
self.timers[self.name] += self.last
5456

55-
return elapsed_time
57+
return self.last
5658

5759
def __enter__(self) -> "Timer":
5860
"""Start a new timer as a context manager"""

tests/test_codetiming.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,15 @@
44
"""
55
# Standard library imports
66
import re
7+
import time
8+
from math import isnan
79

810
# Third party imports
911
import pytest
1012

1113
# Codetiming imports
1214
from codetiming import Timer, TimerError
1315

14-
1516
#
1617
# Test functions
1718
#
@@ -164,3 +165,13 @@ def test_error_if_restarting_running_timer():
164165
t.start()
165166
with pytest.raises(TimerError):
166167
t.start()
168+
169+
170+
def test_timer_sets_last():
171+
t = Timer()
172+
assert isnan(t.last)
173+
t.start()
174+
time.sleep(0.1)
175+
t.stop()
176+
177+
assert 0.1 <= t.last

0 commit comments

Comments
 (0)
0