API reference

Everything below is importable from execution_timer. The public API follows semantic versioning: it only changes incompatibly in a new major version.

from execution_timer import TimerContext, get_execution_times_report

Timing

class execution_timer.TimerContext(name, category=DEFAULT_CATEGORY, counter=None)[source]

Context manager and decorator for timing a named section of code.

Sections entered inside another section are recorded beneath it, so nesting with blocks or decorated calls builds the hierarchy shown in reports. Repeated entries of the same section accumulate their durations. A context can be reused, re-entered while it is active, and shared between threads and asyncio tasks.

Parameters:
  • name (str) – The section’s name within its parent.

  • category (str) – Any string used to group sections, for example "io" or "gpu".

  • counter (int | None) – Records the section as name[counter], typically a loop index. Reports merge these variants unless you pass flatten=False.

Raises:

ValueError – On entry, if a rule from register_forbidden_nesting() forbids this category directly inside the enclosing section’s category.

Example

with TimerContext("load", category="io"):
    data = load()

@TimerContext("solve")
def solve(data): ...
__call__(func)[source]

Decorate a function to time its execution under this context.

Coroutine functions are wrapped so the timing spans the entire await, not just creation of the coroutine object. So is a coroutine returned by a plain function, typically another decorator stacked on an async def.

Raises:

TypeError – If func is a generator or async generator function. A wrapper would time only creation of the generator object, not its iteration.

execution_timer.DEFAULT_CATEGORY: str = "default"

The category of sections created without one.

Reports

execution_timer.get_execution_times_report(*, flatten=True)[source]

Get a formatted, indented report of all recorded sections.

Each line shows a section’s accumulated time and its share of the total time. Indentation reflects nesting. Times have three decimals, in µs, ms or s, whichever keeps the number below 1000.

Parameters:

flatten (bool) – Merge counter variants such as step[0] and step[1] into step.

Returns:

The report, or "" if nothing has been recorded.

Return type:

str

execution_timer.log_execution_times(*, flatten=True, logger=None)[source]

Log the report from get_execution_times_report() at INFO level.

Logs a warning instead if nothing has been recorded. Does nothing, and skips building the report, if the logger has INFO disabled.

Parameters:
  • flatten (bool) – Merge counter variants of a section.

  • logger (Logger | None) – The logger to use. Defaults to the execution_timer._timer logger.

execution_timer.get_execution_timings(*, flatten=True)[source]

Get elapsed seconds and category for every recorded section.

Parameters:

flatten (bool) – Merge counter variants of a section.

Returns:

A new dictionary keyed by section path, such as ("solve", "step"). Changing it does not affect the recorded timings.

Return type:

dict[tuple[str, …], TimingReport]

execution_timer.get_total_time()[source]

Get total elapsed seconds across all top-level sections.

Nested sections are part of their parent’s time, so they are not added again.

Returns:

The total, or 0.0 if nothing has been recorded.

Return type:

float

execution_timer.get_total_category_time(category)[source]

Get total elapsed seconds in a category.

Only the top-most section of the category counts: a section nested inside another of the same category is part of that section’s time and is not added again.

Parameters:

category (str) – The category to total.

Returns:

The total, or 0.0 for a category with no sections.

Return type:

float

JSON export

execution_timer.get_execution_times_json(*, flatten=True, indent=2)[source]

Get all timings as a JSON document shaped like TimingsPayload.

Parameters:
  • flatten (bool) – Merge counter variants of a section.

  • indent (int | None) – Passed to json.dumps(); None gives the most compact output.

Returns:

The JSON text.

Return type:

str

execution_timer.save_execution_timings_json(path, *, flatten=True, indent=2)[source]

Write the JSON from get_execution_times_json() to a UTF-8 file.

Parameters:
  • path (str | Path) – The file to write, replacing it if it exists. Its directory must exist.

  • flatten (bool) – Merge counter variants of a section.

  • indent (int | None) – Passed to json.dumps().

Returns:

The path written to.

Return type:

Path

Managing timings and rules

execution_timer.clear_execution_timings()[source]

Discard all recorded timings.

A section that is active during the clear is not recorded when it exits. Sections started inside it afterwards are recorded as top-level sections. Nesting rules are kept; see clear_forbidden_nesting().

execution_timer.register_forbidden_nesting(outer, inner)[source]

Forbid sections of category inner directly inside sections of category outer.

Entering such a section raises ValueError. Only the direct parent is checked.

Parameters:
  • outer (str) – The enclosing section’s category.

  • inner (str) – The category that may not appear directly inside it.

execution_timer.clear_forbidden_nesting()[source]

Remove all forbidden-nesting rules.

Types

These are TypedDict classes: at runtime the values are plain dictionaries, and the classes exist for type checkers.

class execution_timer.TimingReport[source]

Timing entry for one section, as returned by get_execution_timings().

time: float

Accumulated elapsed seconds.

category: str

The section’s category.

class execution_timer.TimingsPayload[source]

Top-level object of the JSON export from get_execution_times_json().

total_time: float

Seconds across all top-level sections, as returned by get_total_time().

total_category_time: dict[str, float]

Seconds per category, counting only the top-most section of each category.

sections: list[SectionRecord]

Every section, ordered depth-first so children follow their parent.

class execution_timer.SectionRecord[source]

One section in the JSON export, see TimingsPayload.

name: str

The section’s own name, the last element of path.

path: list[str]

Names from the top-level section down to this one.

time: float

Accumulated elapsed seconds, rounded to microseconds.

category: str

The section’s category.

Version

execution_timer.__version__: str

The installed version, for example "1.0.2".