Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions AUTHORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@

## Contributors

- [Jan Freyberg](https://github.com/janfreyberg)
- [Alkatar21](https://github.com/alkatar21)
- [D.C. Hess](https://github.com/dchess)
- [Jan Freyberg](https://github.com/janfreyberg)
- [Mischa Lisovyi](https://github.com/mlisovyi)
- [Matthew Price](https://github.com/pricemg)

See the [changelog](https://github.com/realpython/codetiming/blob/master/CHANGELOG.md) for more details.
See the [changelog](https://github.com/realpython/codetiming/blob/master/CHANGELOG.md) for more details.
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),

## [Unreleased]

### Added

- `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])

## [1.3.2] - 2022-10-07

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

### Changed

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


## [1.1.0] - 2020-01-15
Expand Down Expand Up @@ -81,3 +85,4 @@ Initial version of `codetiming`. Version 1.0.0 corresponds to the code in the tu
[#35]: https://github.com/realpython/codetiming/pull/35
[#38]: https://github.com/realpython/codetiming/pull/38
[#46]: https://github.com/realpython/codetiming/pull/46
[#47]: https://github.com/realpython/codetiming/pull/47
17 changes: 13 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ You can use `codetiming.Timer` in several different ways:
`Timer` accepts the following arguments when it's created. All arguments are optional:

- **`name`:** An optional name for your timer
- **`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"`)
- **`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"`)
- **`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`)
- **`logger`:** A function/callable that takes a string argument and will report the elapsed time when the logger is stopped (default: `print()`)

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

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

```
```python
from humanfriendly import format_timespan

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

You may include a text that should be logged when the timer starts by setting `initial_text`:

```python
t = Timer(initial_text="And so it begins ...")
```

You can also set `initial_text=True` to use a default initial text.


## Capturing the Elapsed Time

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

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:

```python
```pycon
>>> import logging
>>> from codetiming import Timer

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

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

```python
```pycon
>>> Timer.timers.max("example")
3.5836678670002584

Expand Down
11 changes: 11 additions & 0 deletions codetiming/_timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class Timer(ContextDecorator):
_start_time: Optional[float] = field(default=None, init=False, repr=False)
name: Optional[str] = None
text: Union[str, Callable[[float], str]] = "Elapsed time: {:0.4f} seconds"
initial_text: Union[bool, str] = False
logger: Optional[Callable[[str], None]] = print
last: float = field(default=math.nan, init=False, repr=False)

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

# Log initial text when timer starts
if self.logger and self.initial_text:
if isinstance(self.initial_text, str):
initial_text = self.initial_text.format(name=self.name)
elif self.name:
initial_text = "Timer {name} started".format(name=self.name)
else:
initial_text = "Timer started"
self.logger(initial_text)

self._start_time = time.perf_counter()

def stop(self) -> float:
Expand Down
Loading