8000 Add framework for timer startup log statement (#47) · realpython/codetiming@59c13ab · GitHub
[go: up one dir, main page]

Skip to content

Commit 59c13ab

Browse files
pricemggahjelle
andauthored
Add framework for timer startup log statement (#47)
* Add framework for timer startup log statement * Add initial_text attribute to control start text * Add default initial_text referencing timer name * Update CHANGELOG, AUTHORS, and README * A bit of cleanup and tweaks to existing tests Co-authored-by: Geir Arne Hjelle <geirarne@gmail.com>
1 parent ab2a127 commit 59c13ab

File tree

5 files changed

+186
-50
lines changed

5 files changed

+186
-50
lines changed

AUTHORS.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,10 @@
1010

1111
## Contributors
1212

13-
- [Jan Freyberg](https://github.com/janfreyberg)
1413
- [Alkatar21](https://github.com/alkatar21)
1514
- [D.C. Hess](https://github.com/dchess)
15+
- [Jan Freyberg](https://github.com/janfreyberg)
1616
- [Mischa Lisovyi](https://github.com/mlisovyi)
17+
- [Matthew Price](https://github.com/pricemg)
1718

18-
See the [changelog](https://github.com/realpython/codetiming/blob/master/CHANGELOG.md) for more details.
19+
See the [changelog](https://github.com/realpython/codetiming/blob/master/CHANGELOG.md) for more details.

CHANGELOG.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
77

88
## [Unreleased]
99

10+
### Added
11+
12+
- `inital_text` parameter which, when present, will use logger to log that timer has been started (by [Matthew Price](https://github.com/pricemg) in [#47])
13+
1014
## [1.3.2] - 2022-10-07
1115

1216
### Added
@@ -40,7 +44,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
4044

4145
### Changed
4246

43-
- `Timer.timers` changed from regular to `dict` to a custom dictionary supporting basic statistics for named timers ([#23]).
47+
- `Timer.timers` changed from regular `dict` to a custom dictionary supporting basic statistics for named timers ([#23]).
4448

4549

4650
## [1.1.0] - 2020-01-15
@@ -81,3 +85,4 @@ Initial version of `codetiming`. Version 1.0.0 corresponds to the code in the tu
8185
[#35]: https://github.com/realpython/codetiming/pull/35
8286
[#38]: https://github.com/realpython/codetiming/pull/38
8387
[#46]: https://github.com/realpython/codetiming/pull/46
88+
[#47]: https://github.com/realpython/codetiming/pull/47

README.md

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,8 @@ You can use `codetiming.Timer` in several different ways:
5555
`Timer` accepts the following arguments when it's created. All arguments are optional:
5656

5757
- **`name`:** An optional name for your timer
58-
- **`text`:** The text shown when your timer ends. It should contain a `{}` placeholder that will be filled by the elapsed time in seconds (default: `"Elapsed time: {:.4f} seconds"`)
58+
- **`text`:** The text that's shown when your timer ends. It should contain a `{}` placeholder that will be filled by the elapsed time in seconds (default: `"Elapsed time: {:.4f} seconds"`)
59+
- **`initial_text`:** Show text when your timer starts. You may provide the string to be logged or `True` to show the default text `"Timer {name} started"` (default: `False`)
5960
- **`logger`:** A function/callable that takes a string argument and will report the elapsed time when the logger is stopped (default: `print()`)
6061

6162
You can turn off explicit reporting of the elapsed time by setting `logger=None`.
@@ -81,13 +82,21 @@ t = Timer(text=lambda secs: f"{secs / 86400:.0f} days")
8182

8283
This allows you to use third-party libraries like [`humanfriendly`](https://pypi.org/project/humanfriendly/) to do the text formatting:
8384

84-
```
85+
```python
8586
from humanfriendly import format_timespan
8687

8788
t1 = Timer(text=format_timespan)
8889
t2 = Timer(text=lambda secs: f"Elapsed time: {format_timespan(secs)}")
8990
```
9091

92+
You may include a text that should be logged when the timer starts by setting `initial_text`:
93+
94+
```python
95+
t = Timer(initial_text="And so it begins ...")
96+
```
97+
98+
You can also set `initial_text=True` to use a default initial text.
99+
91100

92101
## Capturing the Elapsed Time
93102

@@ -109,7 +118,7 @@ elapsed_time = t.last
109118

110119
Named timers are made available in the class dictionary `Timer.timers`. The elapsed time will accumulate if the same name or same timer is used several times. Consider the following example:
111120

112-
```python
121+
```pycon
113122
>>> import logging
114123
>>> from codetiming import Timer
115124

@@ -133,7 +142,7 @@ The example shows how you can redirect the timer output to the logging module. N
133142

134143
You can also get simple statistics about your named timers. Continuing from the example above:
135144

136-
```python
145+
```pycon
137146
>>> Timer.timers.max("example")
138147
3.5836678670002584
139148

codetiming/_timer.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ class Timer(ContextDecorator):
2727
_start_time: Optional[float] = field(default=None, init=False, repr=False)
2828
name: Optional[str] = None
2929
text: Union[str, Callable[[float], str]] = "Elapsed time: {:0.4f} seconds"
30+
initial_text: Union[bool, str] = False
3031
logger: Optional[Callable[[str], None]] = print
3132
last: float = field(default=math.nan, init=False, repr=False)
3233

@@ -35,6 +36,16 @@ def start(self) -> None:
3536
if self._start_time is not None:
3637
raise TimerError("Timer is running. Use .stop() to stop it")
3738

39+
# Log initial text when timer starts
40+
if self.logger and self.initial_text:
41+
if isinstance(self.initial_text, str):
42+
initial_text = self.initial_text.format(name=self.name)
43+
elif self.name:
44+
initial_text = "Timer {name} started".format(name=self.name)
45+
else:
46+
initial_text = "Timer started"
47+
self.logger(initial_text)
48+
3849
self._start_time = time.perf_counter()
3950

4051
def stop(self) -> float:

0 commit comments

Comments
 (0)
0