executiontimer 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- executiontimer-0.1.0/.gitignore +19 -0
- executiontimer-0.1.0/CHANGELOG.md +33 -0
- executiontimer-0.1.0/LICENSE +21 -0
- executiontimer-0.1.0/PKG-INFO +258 -0
- executiontimer-0.1.0/README.md +229 -0
- executiontimer-0.1.0/pyproject.toml +98 -0
- executiontimer-0.1.0/src/execution_timer/__init__.py +40 -0
- executiontimer-0.1.0/src/execution_timer/_timer.py +362 -0
- executiontimer-0.1.0/src/execution_timer/py.typed +0 -0
- executiontimer-0.1.0/tests/execution_timer_test.py +688 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Byte-compiled / build artifacts
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*.egg-info/
|
|
5
|
+
build/
|
|
6
|
+
dist/
|
|
7
|
+
|
|
8
|
+
# Virtual environments
|
|
9
|
+
.venv/
|
|
10
|
+
|
|
11
|
+
# Tool caches
|
|
12
|
+
.pytest_cache/
|
|
13
|
+
.ruff_cache/
|
|
14
|
+
.basedpyright_cache/
|
|
15
|
+
|
|
16
|
+
# OS
|
|
17
|
+
.DS_Store
|
|
18
|
+
.coverage
|
|
19
|
+
htmlcov/
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [0.1.0] - 2026-08-20
|
|
11
|
+
|
|
12
|
+
First public release on PyPI.
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
|
|
16
|
+
- `TimerContext` — context manager and decorator for timing a named section of code, with
|
|
17
|
+
optional `category` and `counter` arguments.
|
|
18
|
+
- Automatic hierarchical nesting: section names reflect the enclosing timing contexts.
|
|
19
|
+
- Native `async def` support — decorating a coroutine function times the whole `await`
|
|
20
|
+
rather than the creation of the coroutine object.
|
|
21
|
+
- Per-task and per-thread context isolation via `contextvars`, so concurrently recorded
|
|
22
|
+
sections nest independently and merge into one process-wide report.
|
|
23
|
+
- Reporting and export helpers: `get_execution_times_report`, `log_execution_times`,
|
|
24
|
+
`get_execution_timings`, `get_execution_times_json`, `save_execution_timings_json`,
|
|
25
|
+
`get_total_time`, `get_total_category_time`.
|
|
26
|
+
- Optional nesting rules via `register_forbidden_nesting` / `clear_forbidden_nesting`.
|
|
27
|
+
- `clear_execution_timings` to reset the registry.
|
|
28
|
+
- Exported `TimingReport`, `SectionRecord` and `TimingsPayload` typed dictionaries, plus a
|
|
29
|
+
`py.typed` marker so type checkers use the inline annotations.
|
|
30
|
+
- `__version__` attribute on the package.
|
|
31
|
+
|
|
32
|
+
[Unreleased]: https://github.com/seba2390/ExecutionTimer/compare/v0.1.0...HEAD
|
|
33
|
+
[0.1.0]: https://github.com/seba2390/ExecutionTimer/releases/tag/v0.1.0
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sebastian Yde Madsen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: executiontimer
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Hierarchical execution timing with user-defined categories.
|
|
5
|
+
Project-URL: Homepage, https://github.com/seba2390/ExecutionTimer
|
|
6
|
+
Project-URL: Documentation, https://github.com/seba2390/ExecutionTimer#readme
|
|
7
|
+
Project-URL: Repository, https://github.com/seba2390/ExecutionTimer
|
|
8
|
+
Project-URL: Issues, https://github.com/seba2390/ExecutionTimer/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/seba2390/ExecutionTimer/blob/main/CHANGELOG.md
|
|
10
|
+
Author: Sebastian Yde Madsen
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: benchmark,context-manager,decorator,execution-time,instrumentation,performance,profiling,timing
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Intended Audience :: Science/Research
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
|
23
|
+
Classifier: Topic :: Software Development
|
|
24
|
+
Classifier: Topic :: Software Development :: Testing
|
|
25
|
+
Classifier: Topic :: System :: Benchmark
|
|
26
|
+
Classifier: Typing :: Typed
|
|
27
|
+
Requires-Python: >=3.12
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
<p align="center">
|
|
31
|
+
<picture>
|
|
32
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/seba2390/ExecutionTimer/main/assets/logo-dark.svg">
|
|
33
|
+
<source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/seba2390/ExecutionTimer/main/assets/logo-light.svg">
|
|
34
|
+
<img src="https://raw.githubusercontent.com/seba2390/ExecutionTimer/main/assets/logo-light.svg" alt="executiontimer" width="520">
|
|
35
|
+
</picture>
|
|
36
|
+
</p>
|
|
37
|
+
|
|
38
|
+
<p align="center">
|
|
39
|
+
<a href="https://pypi.org/project/executiontimer/"><img src="https://img.shields.io/pypi/v/executiontimer?color=blue" alt="PyPI version"></a>
|
|
40
|
+
<a href="https://pypi.org/project/executiontimer/"><img src="https://img.shields.io/pypi/pyversions/executiontimer" alt="Python versions"></a>
|
|
41
|
+
<a href="https://github.com/seba2390/ExecutionTimer/actions/workflows/ci.yml"><img src="https://github.com/seba2390/ExecutionTimer/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
|
|
42
|
+
<a href="https://github.com/seba2390/ExecutionTimer/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License"></a>
|
|
43
|
+
<img src="https://img.shields.io/badge/types-py.typed-blue" alt="Typed">
|
|
44
|
+
</p>
|
|
45
|
+
|
|
46
|
+
Time named sections of your code with a `with` block or a decorator. Nested sections
|
|
47
|
+
automatically form a hierarchy, so you get a breakdown of where time actually went — not
|
|
48
|
+
just a single number.
|
|
49
|
+
|
|
50
|
+
Zero dependencies. Fully type annotated. Works with threads and `asyncio`.
|
|
51
|
+
|
|
52
|
+
## Features
|
|
53
|
+
|
|
54
|
+
- ⏱️ **One primitive** — `TimerContext` is both a context manager and a decorator
|
|
55
|
+
- 🌳 **Automatic hierarchy** — nesting `with` blocks nests the report, no wiring required
|
|
56
|
+
- 🏷️ **User-defined categories** — tag sections with any string (`"gpu"`, `"io"`, `"db"`) and get per-category totals
|
|
57
|
+
- ⚡ **Native async** — decorating an `async def` times the whole `await`, not the coroutine object
|
|
58
|
+
- 🧵 **Thread and task safe** — context stacks are isolated per thread and per asyncio task
|
|
59
|
+
- 🔢 **Loop counters** — time each iteration separately, then merge them back together
|
|
60
|
+
- 📤 **JSON export** — structured output for dashboards, CI, or an LLM
|
|
61
|
+
- 🚫 **Nesting rules** — optionally forbid one category inside another to catch mistakes early
|
|
62
|
+
- 📦 **Zero dependencies**
|
|
63
|
+
|
|
64
|
+
## Installation
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
pip install executiontimer
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
uv add executiontimer
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Requires Python 3.12+.
|
|
75
|
+
|
|
76
|
+
> **Note** — the install name is `executiontimer`, the import name is `execution_timer`:
|
|
77
|
+
>
|
|
78
|
+
> ```python
|
|
79
|
+
> from execution_timer import TimerContext
|
|
80
|
+
> ```
|
|
81
|
+
|
|
82
|
+
## Quick start
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
import time
|
|
86
|
+
|
|
87
|
+
from execution_timer import TimerContext, get_execution_times_report
|
|
88
|
+
|
|
89
|
+
with TimerContext("load_data"):
|
|
90
|
+
time.sleep(0.12)
|
|
91
|
+
|
|
92
|
+
with TimerContext("solve"):
|
|
93
|
+
for i in range(3):
|
|
94
|
+
with TimerContext("step", category="gpu", counter=i):
|
|
95
|
+
time.sleep(0.05)
|
|
96
|
+
with TimerContext("postprocess", category="cpu"):
|
|
97
|
+
time.sleep(0.03)
|
|
98
|
+
|
|
99
|
+
print(get_execution_times_report())
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
```text
|
|
103
|
+
Total calculation time: 0.3156 s.
|
|
104
|
+
|
|
105
|
+
load_data: 0.1219 s (38.62%)
|
|
106
|
+
solve: 0.1937 s (61.38%)
|
|
107
|
+
.. step: 0.1585 s (50.24%)
|
|
108
|
+
.. postprocess: 0.0350 s (11.10%)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Indentation reflects nesting. Percentages are relative to the total of all top-level
|
|
112
|
+
sections, so nested entries show their share of the whole run.
|
|
113
|
+
|
|
114
|
+
## Usage
|
|
115
|
+
|
|
116
|
+
### As a decorator
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
from execution_timer import TimerContext
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@TimerContext("preprocess")
|
|
123
|
+
def preprocess(rows: list[str]) -> list[str]:
|
|
124
|
+
return [row.strip() for row in rows]
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Coroutine functions are supported natively — the timing spans the entire `await`:
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
@TimerContext("fetch", category="io")
|
|
131
|
+
async def fetch(url: str) -> bytes: ...
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### Counters
|
|
135
|
+
|
|
136
|
+
Pass `counter=i` to time loop iterations separately. The report merges them by default
|
|
137
|
+
(`flatten=True`) and keeps them apart when you ask for it:
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
for i in range(3):
|
|
141
|
+
with TimerContext("step", counter=i):
|
|
142
|
+
...
|
|
143
|
+
|
|
144
|
+
get_execution_timings(flatten=True) # {("step",): {"time": 0.158, ...}}
|
|
145
|
+
get_execution_timings(flatten=False) # {("step[0]",): ..., ("step[1]",): ..., ...}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### Categories
|
|
149
|
+
|
|
150
|
+
Categories are plain strings — use whatever fits your domain:
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
from execution_timer import get_total_category_time
|
|
154
|
+
|
|
155
|
+
with TimerContext("matmul", category="gpu"):
|
|
156
|
+
...
|
|
157
|
+
|
|
158
|
+
get_total_category_time("gpu")
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
`get_total_category_time` counts only the *top-most* section of a category, so a `gpu`
|
|
162
|
+
section nested inside another `gpu` section is not double-counted.
|
|
163
|
+
|
|
164
|
+
You can also forbid a category from appearing inside another, which raises a `ValueError`
|
|
165
|
+
as soon as the invalid nesting happens:
|
|
166
|
+
|
|
167
|
+
```python
|
|
168
|
+
from execution_timer import register_forbidden_nesting
|
|
169
|
+
|
|
170
|
+
register_forbidden_nesting(outer="gpu", inner="cpu")
|
|
171
|
+
|
|
172
|
+
with TimerContext("kernel", category="gpu"):
|
|
173
|
+
with TimerContext("reduce", category="cpu"): # ValueError
|
|
174
|
+
...
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### JSON export
|
|
178
|
+
|
|
179
|
+
`get_execution_times_json` and `save_execution_timings_json` emit a structured snapshot —
|
|
180
|
+
convenient for dashboards, CI artifacts, or handing to a language model:
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
from execution_timer import save_execution_timings_json
|
|
184
|
+
|
|
185
|
+
save_execution_timings_json("timings.json")
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
```json
|
|
189
|
+
{
|
|
190
|
+
"total_time": 0.31556,
|
|
191
|
+
"total_category_time": { "cpu": 0.035024, "default": 0.31556, "gpu": 0.158528 },
|
|
192
|
+
"sections": [
|
|
193
|
+
{ "name": "load_data", "path": ["load_data"], "time": 0.121869, "category": "default" },
|
|
194
|
+
{ "name": "solve", "path": ["solve"], "time": 0.193691, "category": "default" },
|
|
195
|
+
{ "name": "step", "path": ["solve", "step"], "time": 0.158528, "category": "gpu" },
|
|
196
|
+
{ "name": "postprocess", "path": ["solve", "postprocess"], "time": 0.035024, "category": "cpu" }
|
|
197
|
+
]
|
|
198
|
+
}
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
### Concurrency
|
|
202
|
+
|
|
203
|
+
The recorded timings live in one process-wide registry guarded by a lock. The *active
|
|
204
|
+
context stack* is stored in a `ContextVar`, so it is isolated per thread and per asyncio
|
|
205
|
+
task: concurrently recorded sections nest independently and merge into a single report.
|
|
206
|
+
|
|
207
|
+
```python
|
|
208
|
+
async def worker(n: int) -> None:
|
|
209
|
+
with TimerContext(f"task{n}"):
|
|
210
|
+
await fetch(...) # recorded as ("task{n}", "fetch")
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
await asyncio.gather(worker(0), worker(1))
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
Recording the *same* section path from overlapping threads or tasks is not meaningful —
|
|
217
|
+
the elapsed times would overlap and sum to more than the wall-clock duration. Give
|
|
218
|
+
concurrent sections distinct names (or use `counter=`).
|
|
219
|
+
|
|
220
|
+
## API
|
|
221
|
+
|
|
222
|
+
| Function | Description |
|
|
223
|
+
| --- | --- |
|
|
224
|
+
| `TimerContext(name, category=DEFAULT_CATEGORY, counter=None)` | Context manager **and** decorator for timing a section. |
|
|
225
|
+
| `get_execution_times_report(*, flatten=True)` | Formatted, indented report of all sections. |
|
|
226
|
+
| `log_execution_times(*, flatten=True, logger=None)` | Log that report at `INFO` level. |
|
|
227
|
+
| `get_execution_timings(*, flatten=True)` | Timings as `dict[tuple[str, ...], TimingReport]`. |
|
|
228
|
+
| `get_execution_times_json(*, flatten=True, indent=2)` | All timings as a JSON string. |
|
|
229
|
+
| `save_execution_timings_json(path, *, flatten=True, indent=2)` | Write timings to a JSON file; returns the `Path`. |
|
|
230
|
+
| `get_total_time(*, flatten=True)` | Total seconds across all top-level sections. |
|
|
231
|
+
| `get_total_category_time(category)` | Total seconds in a category (top-most entries only). |
|
|
232
|
+
| `clear_execution_timings()` | Reset all recorded timings. |
|
|
233
|
+
| `register_forbidden_nesting(outer, inner)` | Forbid `inner` category directly inside `outer`. |
|
|
234
|
+
| `clear_forbidden_nesting()` | Remove all nesting rules. |
|
|
235
|
+
|
|
236
|
+
`flatten=True` merges `counter` variants of a section back together; `flatten=False`
|
|
237
|
+
keeps each `name[i]` separate.
|
|
238
|
+
|
|
239
|
+
Exported types: `TimingReport`, `SectionRecord`, `TimingsPayload`, and `DEFAULT_CATEGORY`.
|
|
240
|
+
The package ships a `py.typed` marker, so type checkers use the inline annotations.
|
|
241
|
+
|
|
242
|
+
## Development
|
|
243
|
+
|
|
244
|
+
Requires [uv](https://docs.astral.sh/uv/).
|
|
245
|
+
|
|
246
|
+
```bash
|
|
247
|
+
uv sync
|
|
248
|
+
uv run pytest --cov
|
|
249
|
+
uv run ruff check --fix && uv run ruff format
|
|
250
|
+
uv run basedpyright
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for the full workflow, and
|
|
254
|
+
[CHANGELOG.md](CHANGELOG.md) for release notes.
|
|
255
|
+
|
|
256
|
+
## License
|
|
257
|
+
|
|
258
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<picture>
|
|
3
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/seba2390/ExecutionTimer/main/assets/logo-dark.svg">
|
|
4
|
+
<source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/seba2390/ExecutionTimer/main/assets/logo-light.svg">
|
|
5
|
+
<img src="https://raw.githubusercontent.com/seba2390/ExecutionTimer/main/assets/logo-light.svg" alt="executiontimer" width="520">
|
|
6
|
+
</picture>
|
|
7
|
+
</p>
|
|
8
|
+
|
|
9
|
+
<p align="center">
|
|
10
|
+
<a href="https://pypi.org/project/executiontimer/"><img src="https://img.shields.io/pypi/v/executiontimer?color=blue" alt="PyPI version"></a>
|
|
11
|
+
<a href="https://pypi.org/project/executiontimer/"><img src="https://img.shields.io/pypi/pyversions/executiontimer" alt="Python versions"></a>
|
|
12
|
+
<a href="https://github.com/seba2390/ExecutionTimer/actions/workflows/ci.yml"><img src="https://github.com/seba2390/ExecutionTimer/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
|
|
13
|
+
<a href="https://github.com/seba2390/ExecutionTimer/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License"></a>
|
|
14
|
+
<img src="https://img.shields.io/badge/types-py.typed-blue" alt="Typed">
|
|
15
|
+
</p>
|
|
16
|
+
|
|
17
|
+
Time named sections of your code with a `with` block or a decorator. Nested sections
|
|
18
|
+
automatically form a hierarchy, so you get a breakdown of where time actually went — not
|
|
19
|
+
just a single number.
|
|
20
|
+
|
|
21
|
+
Zero dependencies. Fully type annotated. Works with threads and `asyncio`.
|
|
22
|
+
|
|
23
|
+
## Features
|
|
24
|
+
|
|
25
|
+
- ⏱️ **One primitive** — `TimerContext` is both a context manager and a decorator
|
|
26
|
+
- 🌳 **Automatic hierarchy** — nesting `with` blocks nests the report, no wiring required
|
|
27
|
+
- 🏷️ **User-defined categories** — tag sections with any string (`"gpu"`, `"io"`, `"db"`) and get per-category totals
|
|
28
|
+
- ⚡ **Native async** — decorating an `async def` times the whole `await`, not the coroutine object
|
|
29
|
+
- 🧵 **Thread and task safe** — context stacks are isolated per thread and per asyncio task
|
|
30
|
+
- 🔢 **Loop counters** — time each iteration separately, then merge them back together
|
|
31
|
+
- 📤 **JSON export** — structured output for dashboards, CI, or an LLM
|
|
32
|
+
- 🚫 **Nesting rules** — optionally forbid one category inside another to catch mistakes early
|
|
33
|
+
- 📦 **Zero dependencies**
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install executiontimer
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
uv add executiontimer
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Requires Python 3.12+.
|
|
46
|
+
|
|
47
|
+
> **Note** — the install name is `executiontimer`, the import name is `execution_timer`:
|
|
48
|
+
>
|
|
49
|
+
> ```python
|
|
50
|
+
> from execution_timer import TimerContext
|
|
51
|
+
> ```
|
|
52
|
+
|
|
53
|
+
## Quick start
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
import time
|
|
57
|
+
|
|
58
|
+
from execution_timer import TimerContext, get_execution_times_report
|
|
59
|
+
|
|
60
|
+
with TimerContext("load_data"):
|
|
61
|
+
time.sleep(0.12)
|
|
62
|
+
|
|
63
|
+
with TimerContext("solve"):
|
|
64
|
+
for i in range(3):
|
|
65
|
+
with TimerContext("step", category="gpu", counter=i):
|
|
66
|
+
time.sleep(0.05)
|
|
67
|
+
with TimerContext("postprocess", category="cpu"):
|
|
68
|
+
time.sleep(0.03)
|
|
69
|
+
|
|
70
|
+
print(get_execution_times_report())
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
```text
|
|
74
|
+
Total calculation time: 0.3156 s.
|
|
75
|
+
|
|
76
|
+
load_data: 0.1219 s (38.62%)
|
|
77
|
+
solve: 0.1937 s (61.38%)
|
|
78
|
+
.. step: 0.1585 s (50.24%)
|
|
79
|
+
.. postprocess: 0.0350 s (11.10%)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Indentation reflects nesting. Percentages are relative to the total of all top-level
|
|
83
|
+
sections, so nested entries show their share of the whole run.
|
|
84
|
+
|
|
85
|
+
## Usage
|
|
86
|
+
|
|
87
|
+
### As a decorator
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
from execution_timer import TimerContext
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@TimerContext("preprocess")
|
|
94
|
+
def preprocess(rows: list[str]) -> list[str]:
|
|
95
|
+
return [row.strip() for row in rows]
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Coroutine functions are supported natively — the timing spans the entire `await`:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
@TimerContext("fetch", category="io")
|
|
102
|
+
async def fetch(url: str) -> bytes: ...
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### Counters
|
|
106
|
+
|
|
107
|
+
Pass `counter=i` to time loop iterations separately. The report merges them by default
|
|
108
|
+
(`flatten=True`) and keeps them apart when you ask for it:
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
for i in range(3):
|
|
112
|
+
with TimerContext("step", counter=i):
|
|
113
|
+
...
|
|
114
|
+
|
|
115
|
+
get_execution_timings(flatten=True) # {("step",): {"time": 0.158, ...}}
|
|
116
|
+
get_execution_timings(flatten=False) # {("step[0]",): ..., ("step[1]",): ..., ...}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### Categories
|
|
120
|
+
|
|
121
|
+
Categories are plain strings — use whatever fits your domain:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
from execution_timer import get_total_category_time
|
|
125
|
+
|
|
126
|
+
with TimerContext("matmul", category="gpu"):
|
|
127
|
+
...
|
|
128
|
+
|
|
129
|
+
get_total_category_time("gpu")
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`get_total_category_time` counts only the *top-most* section of a category, so a `gpu`
|
|
133
|
+
section nested inside another `gpu` section is not double-counted.
|
|
134
|
+
|
|
135
|
+
You can also forbid a category from appearing inside another, which raises a `ValueError`
|
|
136
|
+
as soon as the invalid nesting happens:
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
from execution_timer import register_forbidden_nesting
|
|
140
|
+
|
|
141
|
+
register_forbidden_nesting(outer="gpu", inner="cpu")
|
|
142
|
+
|
|
143
|
+
with TimerContext("kernel", category="gpu"):
|
|
144
|
+
with TimerContext("reduce", category="cpu"): # ValueError
|
|
145
|
+
...
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### JSON export
|
|
149
|
+
|
|
150
|
+
`get_execution_times_json` and `save_execution_timings_json` emit a structured snapshot —
|
|
151
|
+
convenient for dashboards, CI artifacts, or handing to a language model:
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
from execution_timer import save_execution_timings_json
|
|
155
|
+
|
|
156
|
+
save_execution_timings_json("timings.json")
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
```json
|
|
160
|
+
{
|
|
161
|
+
"total_time": 0.31556,
|
|
162
|
+
"total_category_time": { "cpu": 0.035024, "default": 0.31556, "gpu": 0.158528 },
|
|
163
|
+
"sections": [
|
|
164
|
+
{ "name": "load_data", "path": ["load_data"], "time": 0.121869, "category": "default" },
|
|
165
|
+
{ "name": "solve", "path": ["solve"], "time": 0.193691, "category": "default" },
|
|
166
|
+
{ "name": "step", "path": ["solve", "step"], "time": 0.158528, "category": "gpu" },
|
|
167
|
+
{ "name": "postprocess", "path": ["solve", "postprocess"], "time": 0.035024, "category": "cpu" }
|
|
168
|
+
]
|
|
169
|
+
}
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
### Concurrency
|
|
173
|
+
|
|
174
|
+
The recorded timings live in one process-wide registry guarded by a lock. The *active
|
|
175
|
+
context stack* is stored in a `ContextVar`, so it is isolated per thread and per asyncio
|
|
176
|
+
task: concurrently recorded sections nest independently and merge into a single report.
|
|
177
|
+
|
|
178
|
+
```python
|
|
179
|
+
async def worker(n: int) -> None:
|
|
180
|
+
with TimerContext(f"task{n}"):
|
|
181
|
+
await fetch(...) # recorded as ("task{n}", "fetch")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
await asyncio.gather(worker(0), worker(1))
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Recording the *same* section path from overlapping threads or tasks is not meaningful —
|
|
188
|
+
the elapsed times would overlap and sum to more than the wall-clock duration. Give
|
|
189
|
+
concurrent sections distinct names (or use `counter=`).
|
|
190
|
+
|
|
191
|
+
## API
|
|
192
|
+
|
|
193
|
+
| Function | Description |
|
|
194
|
+
| --- | --- |
|
|
195
|
+
| `TimerContext(name, category=DEFAULT_CATEGORY, counter=None)` | Context manager **and** decorator for timing a section. |
|
|
196
|
+
| `get_execution_times_report(*, flatten=True)` | Formatted, indented report of all sections. |
|
|
197
|
+
| `log_execution_times(*, flatten=True, logger=None)` | Log that report at `INFO` level. |
|
|
198
|
+
| `get_execution_timings(*, flatten=True)` | Timings as `dict[tuple[str, ...], TimingReport]`. |
|
|
199
|
+
| `get_execution_times_json(*, flatten=True, indent=2)` | All timings as a JSON string. |
|
|
200
|
+
| `save_execution_timings_json(path, *, flatten=True, indent=2)` | Write timings to a JSON file; returns the `Path`. |
|
|
201
|
+
| `get_total_time(*, flatten=True)` | Total seconds across all top-level sections. |
|
|
202
|
+
| `get_total_category_time(category)` | Total seconds in a category (top-most entries only). |
|
|
203
|
+
| `clear_execution_timings()` | Reset all recorded timings. |
|
|
204
|
+
| `register_forbidden_nesting(outer, inner)` | Forbid `inner` category directly inside `outer`. |
|
|
205
|
+
| `clear_forbidden_nesting()` | Remove all nesting rules. |
|
|
206
|
+
|
|
207
|
+
`flatten=True` merges `counter` variants of a section back together; `flatten=False`
|
|
208
|
+
keeps each `name[i]` separate.
|
|
209
|
+
|
|
210
|
+
Exported types: `TimingReport`, `SectionRecord`, `TimingsPayload`, and `DEFAULT_CATEGORY`.
|
|
211
|
+
The package ships a `py.typed` marker, so type checkers use the inline annotations.
|
|
212
|
+
|
|
213
|
+
## Development
|
|
214
|
+
|
|
215
|
+
Requires [uv](https://docs.astral.sh/uv/).
|
|
216
|
+
|
|
217
|
+
```bash
|
|
218
|
+
uv sync
|
|
219
|
+
uv run pytest --cov
|
|
220
|
+
uv run ruff check --fix && uv run ruff format
|
|
221
|
+
uv run basedpyright
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for the full workflow, and
|
|
225
|
+
[CHANGELOG.md](CHANGELOG.md) for release notes.
|
|
226
|
+
|
|
227
|
+
## License
|
|
228
|
+
|
|
229
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "executiontimer"
|
|
3
|
+
dynamic = ["version"]
|
|
4
|
+
description = "Hierarchical execution timing with user-defined categories."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.12"
|
|
9
|
+
authors = [{ name = "Sebastian Yde Madsen" }]
|
|
10
|
+
keywords = [
|
|
11
|
+
"timing",
|
|
12
|
+
"profiling",
|
|
13
|
+
"benchmark",
|
|
14
|
+
"execution-time",
|
|
15
|
+
"performance",
|
|
16
|
+
"instrumentation",
|
|
17
|
+
"context-manager",
|
|
18
|
+
"decorator",
|
|
19
|
+
]
|
|
20
|
+
classifiers = [
|
|
21
|
+
"Development Status :: 4 - Beta",
|
|
22
|
+
"Intended Audience :: Developers",
|
|
23
|
+
"Intended Audience :: Science/Research",
|
|
24
|
+
"Operating System :: OS Independent",
|
|
25
|
+
"Programming Language :: Python :: 3",
|
|
26
|
+
"Programming Language :: Python :: 3.12",
|
|
27
|
+
"Programming Language :: Python :: 3.13",
|
|
28
|
+
"Programming Language :: Python :: 3.14",
|
|
29
|
+
"Programming Language :: Python :: Implementation :: CPython",
|
|
30
|
+
"Topic :: Software Development",
|
|
31
|
+
"Topic :: Software Development :: Testing",
|
|
32
|
+
"Topic :: System :: Benchmark",
|
|
33
|
+
"Typing :: Typed",
|
|
34
|
+
]
|
|
35
|
+
dependencies = []
|
|
36
|
+
|
|
37
|
+
[project.urls]
|
|
38
|
+
Homepage = "https://github.com/seba2390/ExecutionTimer"
|
|
39
|
+
Documentation = "https://github.com/seba2390/ExecutionTimer#readme"
|
|
40
|
+
Repository = "https://github.com/seba2390/ExecutionTimer"
|
|
41
|
+
Issues = "https://github.com/seba2390/ExecutionTimer/issues"
|
|
42
|
+
Changelog = "https://github.com/seba2390/ExecutionTimer/blob/main/CHANGELOG.md"
|
|
43
|
+
|
|
44
|
+
[build-system]
|
|
45
|
+
requires = ["hatchling"]
|
|
46
|
+
build-backend = "hatchling.build"
|
|
47
|
+
|
|
48
|
+
[tool.hatch.version]
|
|
49
|
+
path = "src/execution_timer/__init__.py"
|
|
50
|
+
|
|
51
|
+
[tool.hatch.build.targets.wheel]
|
|
52
|
+
packages = ["src/execution_timer"]
|
|
53
|
+
|
|
54
|
+
[tool.hatch.build.targets.sdist]
|
|
55
|
+
include = ["/src", "/tests", "/README.md", "/LICENSE", "/CHANGELOG.md", "/pyproject.toml"]
|
|
56
|
+
|
|
57
|
+
[dependency-groups]
|
|
58
|
+
dev = [
|
|
59
|
+
"basedpyright>=1.39.10",
|
|
60
|
+
"pytest>=9.1.1",
|
|
61
|
+
"pytest-cov>=7.1.0",
|
|
62
|
+
"ruff>=0.16.3",
|
|
63
|
+
]
|
|
64
|
+
|
|
65
|
+
[tool.pytest.ini_options]
|
|
66
|
+
testpaths = ["tests"]
|
|
67
|
+
addopts = "--strict-markers --strict-config"
|
|
68
|
+
|
|
69
|
+
[tool.coverage.run]
|
|
70
|
+
source = ["src/execution_timer"]
|
|
71
|
+
branch = true
|
|
72
|
+
|
|
73
|
+
[tool.coverage.report]
|
|
74
|
+
show_missing = true
|
|
75
|
+
fail_under = 95
|
|
76
|
+
exclude_also = ["if TYPE_CHECKING:", "raise NotImplementedError"]
|
|
77
|
+
|
|
78
|
+
[tool.ruff]
|
|
79
|
+
target-version = "py312"
|
|
80
|
+
line-length = 120
|
|
81
|
+
src = ["src", "tests"]
|
|
82
|
+
|
|
83
|
+
[tool.ruff.lint]
|
|
84
|
+
select = [
|
|
85
|
+
"E", # pycodestyle errors
|
|
86
|
+
"W", # pycodestyle warnings
|
|
87
|
+
"F", # pyflakes
|
|
88
|
+
"I", # isort
|
|
89
|
+
"UP", # pyupgrade
|
|
90
|
+
"B", # flake8-bugbear
|
|
91
|
+
"SIM", # flake8-simplify
|
|
92
|
+
"RUF", # ruff-specific
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
[tool.basedpyright]
|
|
96
|
+
typeCheckingMode = "recommended"
|
|
97
|
+
pythonVersion = "3.12"
|
|
98
|
+
include = ["src", "tests"]
|