executiontimer 0.1.0__py3-none-any.whl
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.
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Hierarchical execution timing with user-defined categories."""
|
|
2
|
+
|
|
3
|
+
from execution_timer._timer import (
|
|
4
|
+
DEFAULT_CATEGORY,
|
|
5
|
+
SectionRecord,
|
|
6
|
+
TimerContext,
|
|
7
|
+
TimingReport,
|
|
8
|
+
TimingsPayload,
|
|
9
|
+
clear_execution_timings,
|
|
10
|
+
clear_forbidden_nesting,
|
|
11
|
+
get_execution_times_json,
|
|
12
|
+
get_execution_times_report,
|
|
13
|
+
get_execution_timings,
|
|
14
|
+
get_total_category_time,
|
|
15
|
+
get_total_time,
|
|
16
|
+
log_execution_times,
|
|
17
|
+
register_forbidden_nesting,
|
|
18
|
+
save_execution_timings_json,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
__version__ = "0.1.0"
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"DEFAULT_CATEGORY",
|
|
25
|
+
"SectionRecord",
|
|
26
|
+
"TimerContext",
|
|
27
|
+
"TimingReport",
|
|
28
|
+
"TimingsPayload",
|
|
29
|
+
"__version__",
|
|
30
|
+
"clear_execution_timings",
|
|
31
|
+
"clear_forbidden_nesting",
|
|
32
|
+
"get_execution_times_json",
|
|
33
|
+
"get_execution_times_report",
|
|
34
|
+
"get_execution_timings",
|
|
35
|
+
"get_total_category_time",
|
|
36
|
+
"get_total_time",
|
|
37
|
+
"log_execution_times",
|
|
38
|
+
"register_forbidden_nesting",
|
|
39
|
+
"save_execution_timings_json",
|
|
40
|
+
]
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
"""Hierarchical execution timing with user-defined categories.
|
|
2
|
+
|
|
3
|
+
Timings are stored in a process-wide registry guarded by a lock. The active-context stack
|
|
4
|
+
lives in a :class:`~contextvars.ContextVar`, so it is isolated per thread *and* per asyncio
|
|
5
|
+
task: sections recorded concurrently nest independently and merge into one report.
|
|
6
|
+
Recording the *same* section path from overlapping threads or tasks is not meaningful.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import functools
|
|
12
|
+
import inspect
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
from collections.abc import Callable, Coroutine, Iterable
|
|
18
|
+
from contextvars import ContextVar
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from types import TracebackType
|
|
21
|
+
from typing import ClassVar, Final, ParamSpec, TypedDict, TypeVar, cast
|
|
22
|
+
|
|
23
|
+
P = ParamSpec("P")
|
|
24
|
+
R = TypeVar("R")
|
|
25
|
+
T = TypeVar("T")
|
|
26
|
+
|
|
27
|
+
DEFAULT_CATEGORY: Final = "default"
|
|
28
|
+
|
|
29
|
+
_LOGGER: Final = logging.getLogger(__name__)
|
|
30
|
+
|
|
31
|
+
# Stack of (name, category) frames for the current thread / asyncio task.
|
|
32
|
+
_ACTIVE_CONTEXT: ContextVar[tuple[tuple[str, str], ...]] = ContextVar("execution_timer_context", default=())
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class TimingReport(TypedDict):
|
|
36
|
+
"""Timing entry for one section: elapsed seconds and its category."""
|
|
37
|
+
|
|
38
|
+
time: float
|
|
39
|
+
category: str
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class SectionRecord(TypedDict):
|
|
43
|
+
"""One section in the JSON export."""
|
|
44
|
+
|
|
45
|
+
name: str
|
|
46
|
+
path: list[str]
|
|
47
|
+
time: float
|
|
48
|
+
category: str
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class TimingsPayload(TypedDict):
|
|
52
|
+
"""Top-level JSON export payload."""
|
|
53
|
+
|
|
54
|
+
total_time: float
|
|
55
|
+
total_category_time: dict[str, float]
|
|
56
|
+
sections: list[SectionRecord]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class _TimesDict(TypedDict):
|
|
60
|
+
start_time: float
|
|
61
|
+
elapsed_time: float
|
|
62
|
+
category: str
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _ordered_by_hierarchy(keys: Iterable[tuple[str, ...]]) -> list[tuple[str, ...]]:
|
|
66
|
+
"""Order section paths depth-first so children always follow their parent.
|
|
67
|
+
|
|
68
|
+
Insertion order is preserved within each level, so a parent revisited after an unrelated
|
|
69
|
+
sibling still renders with its own children rather than beneath the sibling.
|
|
70
|
+
"""
|
|
71
|
+
keys = list(keys)
|
|
72
|
+
known = set(keys)
|
|
73
|
+
children: dict[tuple[str, ...], list[tuple[str, ...]]] = {}
|
|
74
|
+
roots: list[tuple[str, ...]] = []
|
|
75
|
+
for key in keys:
|
|
76
|
+
parent = key[:-1]
|
|
77
|
+
# Treat a section whose parent was never recorded as a root so it cannot be dropped.
|
|
78
|
+
if parent and parent in known:
|
|
79
|
+
children.setdefault(parent, []).append(key)
|
|
80
|
+
else:
|
|
81
|
+
roots.append(key)
|
|
82
|
+
|
|
83
|
+
ordered: list[tuple[str, ...]] = []
|
|
84
|
+
# Explicit stack rather than recursion: nesting depth is user-controlled.
|
|
85
|
+
stack = list(reversed(roots))
|
|
86
|
+
while stack:
|
|
87
|
+
key = stack.pop()
|
|
88
|
+
ordered.append(key)
|
|
89
|
+
stack.extend(reversed(children.get(key, [])))
|
|
90
|
+
return ordered
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class _ExecutionTimer:
|
|
94
|
+
"""Singleton registry of named, nestable timing sections."""
|
|
95
|
+
|
|
96
|
+
_instance: ClassVar[_ExecutionTimer | None] = None
|
|
97
|
+
_lock: ClassVar[threading.Lock] = threading.Lock()
|
|
98
|
+
timings: ClassVar[dict[tuple[str, ...], _TimesDict]] = {}
|
|
99
|
+
forbidden_nesting: ClassVar[set[tuple[str, str]]] = set()
|
|
100
|
+
|
|
101
|
+
def __new__(cls) -> _ExecutionTimer:
|
|
102
|
+
if cls._instance is None:
|
|
103
|
+
cls._instance = super().__new__(cls)
|
|
104
|
+
return cls._instance
|
|
105
|
+
|
|
106
|
+
@property
|
|
107
|
+
def _full_name(self) -> tuple[str, ...]:
|
|
108
|
+
return tuple(frame[0] for frame in _ACTIVE_CONTEXT.get())
|
|
109
|
+
|
|
110
|
+
def _snapshot(self) -> dict[tuple[str, ...], _TimesDict]:
|
|
111
|
+
"""Copy the registry under the lock so readers never iterate a mutating dict."""
|
|
112
|
+
with self._lock:
|
|
113
|
+
return {key: info.copy() for key, info in self.timings.items()}
|
|
114
|
+
|
|
115
|
+
def start_timer(self, name: str, category: str) -> None:
|
|
116
|
+
"""Start timing a section under the given name within the active context."""
|
|
117
|
+
self._add_context(name, category)
|
|
118
|
+
full_name = self._full_name
|
|
119
|
+
start_time = time.perf_counter()
|
|
120
|
+
with self._lock:
|
|
121
|
+
entry = self.timings.get(full_name)
|
|
122
|
+
if entry is None:
|
|
123
|
+
self.timings[full_name] = {"start_time": start_time, "elapsed_time": 0.0, "category": category}
|
|
124
|
+
else:
|
|
125
|
+
entry["start_time"] = start_time
|
|
126
|
+
entry["category"] = category
|
|
127
|
+
|
|
128
|
+
def stop_timer(self, name: str) -> None:
|
|
129
|
+
"""Stop timing a section and accumulate its elapsed time."""
|
|
130
|
+
end_time = time.perf_counter()
|
|
131
|
+
full_name = self._full_name
|
|
132
|
+
with self._lock:
|
|
133
|
+
entry = self.timings.get(full_name)
|
|
134
|
+
# The entry is gone if the registry was cleared while this section was running;
|
|
135
|
+
# dropping the sample is preferable to raising out of a ``with`` block.
|
|
136
|
+
if entry is not None:
|
|
137
|
+
entry["elapsed_time"] += end_time - entry["start_time"]
|
|
138
|
+
self._remove_context(name)
|
|
139
|
+
|
|
140
|
+
def _add_context(self, name: str, category: str) -> None:
|
|
141
|
+
stack = _ACTIVE_CONTEXT.get()
|
|
142
|
+
if stack and (stack[-1][1], category) in self.forbidden_nesting:
|
|
143
|
+
msg = f"Category '{category}' is not allowed inside category '{stack[-1][1]}'."
|
|
144
|
+
raise ValueError(msg)
|
|
145
|
+
_ = _ACTIVE_CONTEXT.set((*stack, (name, category)))
|
|
146
|
+
|
|
147
|
+
def _remove_context(self, name: str) -> None:
|
|
148
|
+
"""Pop the innermost context, restoring the stack to its state before ``name`` was entered."""
|
|
149
|
+
stack = _ACTIVE_CONTEXT.get()
|
|
150
|
+
if not stack:
|
|
151
|
+
return
|
|
152
|
+
# Cut back through the matching frame so a mismatched or out-of-order exit cannot corrupt the stack.
|
|
153
|
+
for index in range(len(stack) - 1, -1, -1):
|
|
154
|
+
if stack[index][0] == name:
|
|
155
|
+
_ = _ACTIVE_CONTEXT.set(stack[:index])
|
|
156
|
+
return
|
|
157
|
+
_ = _ACTIVE_CONTEXT.set(stack[:-1])
|
|
158
|
+
|
|
159
|
+
def compute_flattened_timings(self) -> dict[tuple[str, ...], _TimesDict]:
|
|
160
|
+
"""Aggregate elapsed times with counter suffixes removed from section names.
|
|
161
|
+
|
|
162
|
+
When counter variants of one section are merged, elapsed times are summed and the
|
|
163
|
+
most recently recorded category is kept.
|
|
164
|
+
"""
|
|
165
|
+
return _flatten(self._snapshot())
|
|
166
|
+
|
|
167
|
+
def _resolve(self, *, flatten: bool) -> dict[tuple[str, ...], _TimesDict]:
|
|
168
|
+
snapshot = self._snapshot()
|
|
169
|
+
return _flatten(snapshot) if flatten else snapshot
|
|
170
|
+
|
|
171
|
+
def report_timings(self, *, flatten: bool = True) -> str:
|
|
172
|
+
"""Build a report of all sections with duration and percentage of total time."""
|
|
173
|
+
timings = self._resolve(flatten=flatten)
|
|
174
|
+
if not timings:
|
|
175
|
+
_LOGGER.warning("No timings to report.")
|
|
176
|
+
return ""
|
|
177
|
+
|
|
178
|
+
total_time = sum(info["elapsed_time"] for key, info in timings.items() if len(key) == 1)
|
|
179
|
+
report = [f"\nTotal calculation time: {total_time:.4f} s.\n"]
|
|
180
|
+
for key in _ordered_by_hierarchy(timings):
|
|
181
|
+
elapsed_time = timings[key]["elapsed_time"]
|
|
182
|
+
percentage = (elapsed_time / total_time) * 100 if total_time else 0.0
|
|
183
|
+
report.append(f"{'.. ' * (len(key) - 1)}{key[-1]}: {elapsed_time:.4f} s ({percentage:.2f}%)")
|
|
184
|
+
return "\n".join(report)
|
|
185
|
+
|
|
186
|
+
def compute_total_time(self, *, flatten: bool = True) -> float:
|
|
187
|
+
"""Compute total elapsed time across all top-level sections."""
|
|
188
|
+
timings = self._resolve(flatten=flatten)
|
|
189
|
+
return sum(info["elapsed_time"] for key, info in timings.items() if len(key) == 1)
|
|
190
|
+
|
|
191
|
+
def compute_total_category_time(self, category: str) -> float:
|
|
192
|
+
"""Compute total elapsed time in a category, counting only top-most entries of that category."""
|
|
193
|
+
timings = self._snapshot()
|
|
194
|
+
total_time = 0.0
|
|
195
|
+
for key, info in timings.items():
|
|
196
|
+
if info["category"] != category or _has_ancestor_with_category(timings, key, category):
|
|
197
|
+
continue
|
|
198
|
+
total_time += info["elapsed_time"]
|
|
199
|
+
return total_time
|
|
200
|
+
|
|
201
|
+
def get_execution_timings(self, *, flatten: bool = True) -> dict[tuple[str, ...], TimingReport]:
|
|
202
|
+
"""Return elapsed seconds and category for every recorded section."""
|
|
203
|
+
timings = self._resolve(flatten=flatten)
|
|
204
|
+
return {key: {"time": info["elapsed_time"], "category": info["category"]} for key, info in timings.items()}
|
|
205
|
+
|
|
206
|
+
def clear(self) -> None:
|
|
207
|
+
"""Drop every recorded section."""
|
|
208
|
+
with self._lock:
|
|
209
|
+
self.timings.clear()
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _flatten(timings: dict[tuple[str, ...], _TimesDict]) -> dict[tuple[str, ...], _TimesDict]:
|
|
213
|
+
flat_map: dict[tuple[str, ...], _TimesDict] = {}
|
|
214
|
+
for key, info in timings.items():
|
|
215
|
+
flat_key = tuple(_basic_name_without_counter(part) for part in key)
|
|
216
|
+
existing = flat_map.get(flat_key)
|
|
217
|
+
if existing is None:
|
|
218
|
+
flat_map[flat_key] = info.copy()
|
|
219
|
+
else:
|
|
220
|
+
existing["elapsed_time"] += info["elapsed_time"]
|
|
221
|
+
existing["category"] = info["category"]
|
|
222
|
+
return flat_map
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _has_ancestor_with_category(
|
|
226
|
+
timings: dict[tuple[str, ...], _TimesDict], key: tuple[str, ...], category: str
|
|
227
|
+
) -> bool:
|
|
228
|
+
return any(key[:i] in timings and timings[key[:i]]["category"] == category for i in range(1, len(key)))
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class TimerContext:
|
|
232
|
+
"""Context manager and decorator for timing a named section of code."""
|
|
233
|
+
|
|
234
|
+
def __init__(self, name: str, category: str = DEFAULT_CATEGORY, counter: int | None = None) -> None:
|
|
235
|
+
self.name: str = _build_name_with_counter(name, counter)
|
|
236
|
+
self.category: str = category
|
|
237
|
+
self.timer: _ExecutionTimer = _ExecutionTimer()
|
|
238
|
+
|
|
239
|
+
def __enter__(self) -> TimerContext:
|
|
240
|
+
self.timer.start_timer(self.name, self.category)
|
|
241
|
+
return self
|
|
242
|
+
|
|
243
|
+
def __exit__(
|
|
244
|
+
self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None
|
|
245
|
+
) -> None:
|
|
246
|
+
self.timer.stop_timer(self.name)
|
|
247
|
+
|
|
248
|
+
def __call__(self, func: Callable[P, R]) -> Callable[P, R]:
|
|
249
|
+
"""Decorate a function to time its execution under this context.
|
|
250
|
+
|
|
251
|
+
Coroutine functions are wrapped so the timing spans the entire ``await``, not just
|
|
252
|
+
creation of the coroutine object.
|
|
253
|
+
"""
|
|
254
|
+
if inspect.iscoroutinefunction(func):
|
|
255
|
+
# ``iscoroutinefunction`` narrows nothing useful for the type checker, so bridge
|
|
256
|
+
# through an explicitly typed helper instead of leaking ``Any`` into the signature.
|
|
257
|
+
async_func = cast("Callable[P, Coroutine[object, object, object]]", func)
|
|
258
|
+
return cast("Callable[P, R]", self._wrap_async(async_func))
|
|
259
|
+
|
|
260
|
+
@functools.wraps(func)
|
|
261
|
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
|
262
|
+
with TimerContext(self.name, self.category):
|
|
263
|
+
return func(*args, **kwargs)
|
|
264
|
+
|
|
265
|
+
return wrapper
|
|
266
|
+
|
|
267
|
+
def _wrap_async(self, func: Callable[P, Coroutine[object, object, T]]) -> Callable[P, Coroutine[object, object, T]]:
|
|
268
|
+
"""Wrap a coroutine function so the timing spans the whole await."""
|
|
269
|
+
|
|
270
|
+
@functools.wraps(func)
|
|
271
|
+
async def async_wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
|
|
272
|
+
with TimerContext(self.name, self.category):
|
|
273
|
+
return await func(*args, **kwargs)
|
|
274
|
+
|
|
275
|
+
return async_wrapper
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _build_name_with_counter(name: str, counter: int | None = None) -> str:
|
|
279
|
+
"""Append ``[counter]`` to a section name if a counter is provided."""
|
|
280
|
+
if counter is None:
|
|
281
|
+
return name
|
|
282
|
+
return f"{name}[{counter}]"
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _basic_name_without_counter(name: str) -> str:
|
|
286
|
+
"""Strip a trailing ``[counter]`` from a section name if present."""
|
|
287
|
+
if "[" in name and name.endswith("]"):
|
|
288
|
+
return name[: name.rfind("[")]
|
|
289
|
+
return name
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def get_execution_times_report(*, flatten: bool = True) -> str:
|
|
293
|
+
"""Get a formatted report of all recorded sections; flatten counters if requested."""
|
|
294
|
+
return _ExecutionTimer().report_timings(flatten=flatten)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def log_execution_times(*, flatten: bool = True, logger: logging.Logger | None = None) -> None:
|
|
298
|
+
"""Log the execution-times report at INFO level; flatten counters if requested."""
|
|
299
|
+
(logger or _LOGGER).info(get_execution_times_report(flatten=flatten))
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def get_execution_timings(*, flatten: bool = True) -> dict[tuple[str, ...], TimingReport]:
|
|
303
|
+
"""Get elapsed seconds and category for every recorded section; flatten counters if requested."""
|
|
304
|
+
return _ExecutionTimer().get_execution_timings(flatten=flatten)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _build_payload(*, flatten: bool = True) -> TimingsPayload:
|
|
308
|
+
"""Build a JSON-serializable snapshot of all timings, including totals and per-category sums."""
|
|
309
|
+
timer = _ExecutionTimer()
|
|
310
|
+
timings = timer.get_execution_timings(flatten=flatten)
|
|
311
|
+
sections: list[SectionRecord] = [
|
|
312
|
+
{
|
|
313
|
+
"name": key[-1],
|
|
314
|
+
"path": list(key),
|
|
315
|
+
"time": round(timings[key]["time"], 6),
|
|
316
|
+
"category": timings[key]["category"],
|
|
317
|
+
}
|
|
318
|
+
for key in _ordered_by_hierarchy(timings)
|
|
319
|
+
]
|
|
320
|
+
categories = sorted({info["category"] for info in timings.values()})
|
|
321
|
+
return {
|
|
322
|
+
"total_time": round(timer.compute_total_time(flatten=flatten), 6),
|
|
323
|
+
"total_category_time": {cat: round(timer.compute_total_category_time(cat), 6) for cat in categories},
|
|
324
|
+
"sections": sections,
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def get_execution_times_json(*, flatten: bool = True, indent: int | None = 2) -> str:
|
|
329
|
+
"""Get all timings as a JSON string (LLM-friendly); flatten counters if requested."""
|
|
330
|
+
return json.dumps(_build_payload(flatten=flatten), indent=indent)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def save_execution_timings_json(path: str | Path, *, flatten: bool = True, indent: int | None = 2) -> Path:
|
|
334
|
+
"""Write all timings to a JSON file and return its path; flatten counters if requested."""
|
|
335
|
+
out = Path(path)
|
|
336
|
+
_ = out.write_text(get_execution_times_json(flatten=flatten, indent=indent) + "\n", encoding="utf-8")
|
|
337
|
+
return out
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def get_total_time(*, flatten: bool = True) -> float:
|
|
341
|
+
"""Get total elapsed seconds across all top-level sections."""
|
|
342
|
+
return _ExecutionTimer().compute_total_time(flatten=flatten)
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def get_total_category_time(category: str) -> float:
|
|
346
|
+
"""Get total elapsed seconds in a category, counting only top-most entries of that category."""
|
|
347
|
+
return _ExecutionTimer().compute_total_category_time(category)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def clear_execution_timings() -> None:
|
|
351
|
+
"""Reset all recorded timings."""
|
|
352
|
+
_ExecutionTimer().clear()
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def register_forbidden_nesting(outer: str, inner: str) -> None:
|
|
356
|
+
"""Forbid timing sections of category ``inner`` directly inside sections of category ``outer``."""
|
|
357
|
+
_ExecutionTimer.forbidden_nesting.add((outer, inner))
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def clear_forbidden_nesting() -> None:
|
|
361
|
+
"""Remove all forbidden-nesting rules."""
|
|
362
|
+
_ExecutionTimer.forbidden_nesting = set()
|
execution_timer/py.typed
ADDED
|
File without changes
|
|
@@ -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,7 @@
|
|
|
1
|
+
execution_timer/__init__.py,sha256=6DKOLTSXY0gu_DjW_rIqBRZROUYnlp8haVYvLX6NzTQ,959
|
|
2
|
+
execution_timer/_timer.py,sha256=USfPpUdpW3jk1ffjIcTdOmB-FK-8HQHgcvZ44mJQ2f4,14504
|
|
3
|
+
execution_timer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
executiontimer-0.1.0.dist-info/METADATA,sha256=1ftfFmuikQRb6w1mmfZAUVdezEUUgyweDkxE8ljTLNY,9412
|
|
5
|
+
executiontimer-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
6
|
+
executiontimer-0.1.0.dist-info/licenses/LICENSE,sha256=rkJbDOYRrUX8k3S55pPiEquJXZGh07KvD01F1sBBppw,1077
|
|
7
|
+
executiontimer-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|