executiontimer 1.0.0__py3-none-any.whl → 1.0.2__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.
@@ -18,7 +18,7 @@ from execution_timer._timer import (
18
18
  save_execution_timings_json,
19
19
  )
20
20
 
21
- __version__ = "1.0.0"
21
+ __version__ = "1.0.2"
22
22
 
23
23
  __all__ = [
24
24
  "DEFAULT_CATEGORY",
execution_timer/_timer.py CHANGED
@@ -74,11 +74,13 @@ class _Frame(NamedTuple):
74
74
  _ACTIVE_CONTEXT: ContextVar[_Frame | None] = ContextVar("execution_timer_context", default=None)
75
75
 
76
76
 
77
- def _ordered_by_hierarchy(keys: Iterable[tuple[str, ...]]) -> list[tuple[str, ...]]:
77
+ def _ordered_by_hierarchy(keys: Iterable[tuple[str, ...]]) -> list[tuple[tuple[str, ...], int]]:
78
78
  """Order section paths depth-first so children always follow their parent.
79
79
 
80
- Insertion order is preserved within each level, so a parent revisited after an unrelated
81
- sibling still renders with its own children rather than beneath the sibling.
80
+ Returns each path with its depth in the recorded tree, which is shallower than the path
81
+ length when an ancestor is missing. Insertion order is preserved within each level, so a
82
+ parent revisited after an unrelated sibling still renders with its own children rather
83
+ than beneath the sibling.
82
84
  """
83
85
  keys = list(keys)
84
86
  known = set(keys)
@@ -92,16 +94,28 @@ def _ordered_by_hierarchy(keys: Iterable[tuple[str, ...]]) -> list[tuple[str, ..
92
94
  else:
93
95
  roots.append(key)
94
96
 
95
- ordered: list[tuple[str, ...]] = []
97
+ ordered: list[tuple[tuple[str, ...], int]] = []
96
98
  # Explicit stack rather than recursion: nesting depth is user-controlled.
97
- stack = list(reversed(roots))
99
+ stack = [(key, 0) for key in reversed(roots)]
98
100
  while stack:
99
- key = stack.pop()
100
- ordered.append(key)
101
- stack.extend(reversed(children.get(key, [])))
101
+ key, depth = stack.pop()
102
+ ordered.append((key, depth))
103
+ stack.extend((child, depth + 1) for child in reversed(children.get(key, [])))
102
104
  return ordered
103
105
 
104
106
 
107
+ def _top_level_time(timings: dict[tuple[str, ...], _TimesDict]) -> float:
108
+ """Sum the sections with no recorded parent, matching the roots of ``_ordered_by_hierarchy``.
109
+
110
+ A parent goes missing when timings are cleared while it is active; its children that
111
+ finish afterwards are then top-level and must count toward the total.
112
+ """
113
+ return sum(
114
+ (info["elapsed_time"] for key, info in timings.items() if len(key) == 1 or key[:-1] not in timings),
115
+ 0.0,
116
+ )
117
+
118
+
105
119
  class _ExecutionTimer:
106
120
  """Registry of named, nestable timing sections, shared through ``_TIMER``."""
107
121
 
@@ -137,9 +151,10 @@ class _ExecutionTimer:
137
151
  def stop_timer(self, name: str) -> None:
138
152
  """Stop timing a section and accumulate its elapsed time.
139
153
 
140
- Never raises: an exception here would replace one already propagating from the timed
141
- block. Exiting past still-active inner sections (typically a suspended generator that
142
- holds one open) discards them with a warning, so the stack cannot stay corrupted.
154
+ Never raises, unless warnings are configured as errors: an exception here would replace
155
+ one already propagating from the timed block. Exiting past still-active inner sections
156
+ (typically a suspended generator that holds one open) discards them with a warning,
157
+ after recording the exit, so the stack cannot stay corrupted.
143
158
  Exiting a section that is no longer active, such as one discarded that way when its
144
159
  generator is finally closed, does nothing.
145
160
  """
@@ -150,17 +165,18 @@ class _ExecutionTimer:
150
165
  frame = frame.parent
151
166
  if frame is None:
152
167
  return
168
+ with self._lock:
169
+ # A clear detaches this entry from the registry. Updating the detached object
170
+ # cannot resurrect an old sample or add it to a replacement at the same path.
171
+ frame.entry["elapsed_time"] += end_time - frame.start_time
172
+ _ = _ACTIVE_CONTEXT.set(frame.parent)
153
173
  if frame is not active and active is not None:
174
+ # Warn only once the state is consistent: warnings configured as errors raise here.
154
175
  msg = (
155
176
  f"Section '{name}' exited while '{active.path[-1]}' was still active; discarding the "
156
177
  "unfinished inner sections. Close sections before a generator yields."
157
178
  )
158
179
  warnings.warn(msg, RuntimeWarning, stacklevel=3)
159
- with self._lock:
160
- # A clear detaches this entry from the registry. Updating the detached object
161
- # cannot resurrect an old sample or add it to a replacement at the same path.
162
- frame.entry["elapsed_time"] += end_time - frame.start_time
163
- _ = _ACTIVE_CONTEXT.set(frame.parent)
164
180
 
165
181
  def _resolve(self, *, flatten: bool) -> dict[tuple[str, ...], _TimesDict]:
166
182
  snapshot = self.snapshot()
@@ -168,23 +184,25 @@ class _ExecutionTimer:
168
184
 
169
185
  def report_timings(self, *, flatten: bool = True) -> str:
170
186
  """Build a report of all sections with duration and percentage of total time."""
171
- timings = self._resolve(flatten=flatten)
172
- if not timings:
187
+ snapshot = self.snapshot()
188
+ if not snapshot:
173
189
  return ""
174
190
 
175
- total_time = sum(info["elapsed_time"] for key, info in timings.items() if len(key) == 1)
191
+ # Total the unflattened paths, like get_total_time and the JSON export.
192
+ total_time = _top_level_time(snapshot)
193
+ timings = _flatten(snapshot) if flatten else snapshot
176
194
  report = [f"Total time: {total_time:.4f} s.\n"]
177
- for key in _ordered_by_hierarchy(timings):
195
+ for key, depth in _ordered_by_hierarchy(timings):
178
196
  elapsed_time = timings[key]["elapsed_time"]
179
197
  percentage = (elapsed_time / total_time) * 100 if total_time else 0.0
180
- report.append(f"{'.. ' * (len(key) - 1)}{key[-1]}: {elapsed_time:.4f} s ({percentage:.2f}%)")
198
+ report.append(f"{'.. ' * depth}{key[-1]}: {elapsed_time:.4f} s ({percentage:.2f}%)")
181
199
  return "\n".join(report)
182
200
 
183
201
  def compute_total_time(self) -> float:
184
202
  """Compute total elapsed time across all top-level sections."""
185
203
  # Counter merging cannot change the sum, so there is no snapshot to copy or flatten.
186
204
  with self._lock:
187
- return sum((info["elapsed_time"] for key, info in self.timings.items() if len(key) == 1), 0.0)
205
+ return _top_level_time(self.timings)
188
206
 
189
207
  def compute_total_category_time(self, category: str) -> float:
190
208
  """Compute total elapsed time in a category, counting only top-most entries of that category."""
@@ -260,8 +278,9 @@ class TimerContext:
260
278
  """Decorate a function to time its execution under this context.
261
279
 
262
280
  Coroutine functions are wrapped so the timing spans the entire ``await``, not just
263
- creation of the coroutine object. Generator functions are rejected: a wrapper would
264
- time only creation of the generator object, not its iteration.
281
+ creation of the coroutine object. So is a coroutine returned by a plain function,
282
+ typically another decorator stacked on an ``async def``. Generator functions are
283
+ rejected: a wrapper would time only creation of the generator object, not its iteration.
265
284
  """
266
285
  if inspect.isgeneratorfunction(func) or inspect.isasyncgenfunction(func):
267
286
  msg = (
@@ -279,10 +298,20 @@ class TimerContext:
279
298
  @functools.wraps(func)
280
299
  def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
281
300
  with self:
282
- return func(*args, **kwargs)
301
+ result = func(*args, **kwargs)
302
+ if inspect.iscoroutine(result):
303
+ # A decorator between this one and an ``async def`` hides the coroutine function,
304
+ # so the call above only created the coroutine. Time awaiting it as well.
305
+ return cast("R", self._time_await(result))
306
+ return result
283
307
 
284
308
  return wrapper
285
309
 
310
+ async def _time_await(self, coroutine: Coroutine[object, object, T]) -> T:
311
+ """Await a coroutine that was created outside this context, timing the whole await."""
312
+ with self:
313
+ return await coroutine
314
+
286
315
  def _wrap_async(self, func: Callable[P, Coroutine[object, object, T]]) -> Callable[P, Coroutine[object, object, T]]:
287
316
  """Wrap a coroutine function so the timing spans the whole await."""
288
317
 
@@ -344,7 +373,7 @@ def _build_payload(*, flatten: bool = True) -> TimingsPayload:
344
373
  "time": round(timings[key]["elapsed_time"], 6),
345
374
  "category": timings[key]["category"],
346
375
  }
347
- for key in _ordered_by_hierarchy(timings)
376
+ for key, _ in _ordered_by_hierarchy(timings)
348
377
  ]
349
378
  category_totals: dict[str, float] = {}
350
379
  for key, info in snapshot.items():
@@ -352,7 +381,7 @@ def _build_payload(*, flatten: bool = True) -> TimingsPayload:
352
381
  if not _has_ancestor_with_category(snapshot, key, category):
353
382
  category_totals[category] = category_totals.get(category, 0.0) + info["elapsed_time"]
354
383
  return {
355
- "total_time": round(sum((info["elapsed_time"] for key, info in snapshot.items() if len(key) == 1), 0.0), 6),
384
+ "total_time": round(_top_level_time(snapshot), 6),
356
385
  "total_category_time": {cat: round(category_totals[cat], 6) for cat in sorted(category_totals)},
357
386
  "sections": sections,
358
387
  }
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: executiontimer
3
- Version: 1.0.0
3
+ Version: 1.0.2
4
4
  Summary: Hierarchical execution timing with user-defined categories.
5
5
  Project-URL: Homepage, https://github.com/seba2390/ExecutionTimer
6
6
  Project-URL: Documentation, https://github.com/seba2390/ExecutionTimer#readme
@@ -134,6 +134,9 @@ Coroutine functions are supported natively — the timing spans the entire `awai
134
134
  async def fetch(url: str) -> bytes: ...
135
135
  ```
136
136
 
137
+ This also holds when another decorator sits between `TimerContext` and the `async def`
138
+ and returns its coroutine: the section covers both the call and the `await`.
139
+
137
140
  Generator functions (including `async` generators) cannot be decorated and raise a
138
141
  `TypeError`: the decorator would time only the creation of the generator object, not its
139
142
  iteration. Time the loop that consumes the generator with a `with` block instead.
@@ -153,7 +156,9 @@ get_execution_timings(flatten=False) # {("step[0]",): ..., ("step[1]",): ..., .
153
156
  ```
154
157
 
155
158
  Flattening removes the final integer suffix (including negative counters). Other
156
- bracketed names such as `array[index]` are preserved. If merged entries have different
159
+ bracketed names such as `array[index]` are preserved. Flattening cannot tell a counter
160
+ from a name you wrote yourself, so sections named `"row[1]"` and `"row[2]"` are also merged
161
+ into `row`; use `flatten=False` to keep them apart. If merged entries have different
157
162
  categories, the category from the most recently entered section is used.
158
163
 
159
164
  Each counter value is stored as its own section until `clear_execution_timings()` is
@@ -260,7 +265,8 @@ time the loop that consumes the generator instead.
260
265
  If the caller's section exits while a paused generator's section is still open, the
261
266
  timer never raises: it emits a `RuntimeWarning`, records the caller's section, and
262
267
  discards the generator's unfinished one, so later sections nest correctly. Closing that
263
- generator afterwards does nothing.
268
+ generator afterwards does nothing. If warnings are configured as errors, the warning is
269
+ raised only after that cleanup, so the timings and nesting stay consistent.
264
270
 
265
271
  ### Reusing contexts and clearing timings
266
272
 
@@ -276,7 +282,8 @@ for item in items:
276
282
 
277
283
  Timings accumulate until `clear_execution_timings()` is called. Clearing also discards
278
284
  samples from sections that were already active, without disturbing their nesting stack.
279
- Sections started after the clear are recorded normally. Reports include completed calls;
285
+ Sections started after the clear are recorded normally; if their parent was cleared, they
286
+ are reported as top-level sections and count toward the total. Reports include completed calls;
280
287
  an active section's current duration is added only when it exits.
281
288
 
282
289
  ### Measuring overhead
@@ -284,7 +291,6 @@ an active section's current duration is added only when it exits.
284
291
  Run the repeatable benchmark with `uv run python benchmarks/overhead.py`. It measures
285
292
  fresh and reused contexts, sync and async decorators, nesting, and reporting. Compare
286
293
  results using the same interpreter and machine; see [benchmarks/README.md](https://github.com/seba2390/ExecutionTimer/blob/main/benchmarks/README.md).
287
- `log_execution_times()` skips building a report when its logger has `INFO` disabled.
288
294
 
289
295
  ## API
290
296
 
@@ -292,7 +298,7 @@ results using the same interpreter and machine; see [benchmarks/README.md](https
292
298
  | --- | --- |
293
299
  | `TimerContext(name, category=DEFAULT_CATEGORY, counter=None)` | Context manager **and** decorator for timing a section. |
294
300
  | `get_execution_times_report(*, flatten=True)` | Formatted, indented report of all sections (`""` if none). |
295
- | `log_execution_times(*, flatten=True, logger=None)` | Log that report at `INFO` level (a warning if empty). |
301
+ | `log_execution_times(*, flatten=True, logger=None)` | Log that report at `INFO` level (a warning if empty); a no-op if `INFO` is disabled. |
296
302
  | `get_execution_timings(*, flatten=True)` | Timings as `dict[tuple[str, ...], TimingReport]`. |
297
303
  | `get_execution_times_json(*, flatten=True, indent=2)` | All timings as a JSON string. |
298
304
  | `save_execution_timings_json(path, *, flatten=True, indent=2)` | Write timings to a JSON file; returns the `Path`. |
@@ -0,0 +1,7 @@
1
+ execution_timer/__init__.py,sha256=WBDnG2RxhKZmuhb5U4wgVV4WNgvZehegtfBuSh7AA6I,959
2
+ execution_timer/_timer.py,sha256=ermOhB2xWM4acsGgkHuN3MyeA9uqpa9FgNuoAABdGjY,17439
3
+ execution_timer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ executiontimer-1.0.2.dist-info/METADATA,sha256=7hk9S89FJ0b9H-O2IAWak-c_ef55RS1Vq1pJPh4gCGY,13900
5
+ executiontimer-1.0.2.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
6
+ executiontimer-1.0.2.dist-info/licenses/LICENSE,sha256=rkJbDOYRrUX8k3S55pPiEquJXZGh07KvD01F1sBBppw,1077
7
+ executiontimer-1.0.2.dist-info/RECORD,,
@@ -1,7 +0,0 @@
1
- execution_timer/__init__.py,sha256=gv9IbtkZkesfgWFh1oDSJ5DDr2BJFVxmKtY32jcUzbI,959
2
- execution_timer/_timer.py,sha256=iylgfJ1vBeKimsW5A3NVN5KSUvZs75Km-N4guoHKFPo,15932
3
- execution_timer/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
- executiontimer-1.0.0.dist-info/METADATA,sha256=ZtN7WHMrB8gTaGIy0VQLHDtu2ySFvd8oZx56KmA5F8s,13386
5
- executiontimer-1.0.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
6
- executiontimer-1.0.0.dist-info/licenses/LICENSE,sha256=rkJbDOYRrUX8k3S55pPiEquJXZGh07KvD01F1sBBppw,1077
7
- executiontimer-1.0.0.dist-info/RECORD,,