Skip to content

xtr_stopwatch

Times what code does: named events, grouped by category, nested in sections.

A profile wants to know where a request spent its time — which listener, which query, which template — and on one axis, so the pieces can be drawn as a timeline. :class:~xtr_stopwatch.stopwatch.Stopwatch records exactly that: each event is a name, a category and the periods it ran for, and every event of a section is measured from the section's own origin.

What is timed belongs to the calling context, so concurrent requests served by one process each see only their own events.

ROOT module-attribute

ROOT: Final = '__root__'

The id the root section is kept under.

SECTION_CATEGORY module-attribute

SECTION_CATEGORY: Final = 'section'

The category of the event spanning a child section.

SECTION_CHILD_EVENT module-attribute

SECTION_CHILD_EVENT: Final = '__section__.child'

The event spanning a child section, kept in the section that opened it.

SECTION_EVENT module-attribute

SECTION_EVENT: Final = '__section__'

The event spanning a section, started in it as it opens and stopped as it closes.

EventNotStartedError

EventNotStartedError(name: str)

Bases: StopwatchError

An event was stopped, or lapped, while it was not running.

A stop with no start to pair it with has no period to close, so it is refused rather than recorded as nothing.

Attributes:

  • name (str) –

    The event that was not running.

Record the event that was not running.

NoStartedSectionError

NoStartedSectionError(section_id: str)

Bases: StopwatchError

A section was stopped while none was open.

The root section is always open and is never stopped, so stopping with only the root in place has nothing to stop.

Attributes:

  • section_id (str) –

    The id the section would have been stored under.

Record the id the stop was asked for.

StopwatchError

Bases: Exception

Base class for every error raised by this library.

Catch this to handle anything timing can go wrong with; catch a subclass to handle one cause. Every subclass carries what went wrong as typed attributes and composes its own message from them.

UnknownEventError

UnknownEventError(name: str)

Bases: StopwatchError, LookupError

An event was asked for that the current section never started.

Also a :class:LookupError, as a missing key is.

Attributes:

  • name (str) –

    The event that is not known.

Record the event that is not known.

UnknownSectionError

UnknownSectionError(section_id: str)

Bases: StopwatchError, LookupError

A section was reopened by an id the current section holds no child under.

Reopening adds periods to a section that was stopped earlier, and that is only meaningful at the level it lives at: a section started elsewhere is refused rather than silently begun afresh here.

Also a :class:LookupError, as a missing key is.

Attributes:

  • section_id (str) –

    The id that is not a child of the current section.

Record the id that was asked for.

Section

Section(origin: float | None = None, clock: ClockInterface | None = None)

Holds the events timed while it was the current section.

A section measures every event it holds from one origin — the instant it was opened — so its events line up on one timeline. The root section has no origin of its own; each of its events is measured from the instant it first started.

Make a section measuring its events from origin.

Parameters:

  • origin (float | None, default: None ) –

    The instant the section began, in milliseconds since the epoch; None for the root.

  • clock (ClockInterface | None, default: None ) –

    What time is read from. None uses a :class:~xtr_clock.MonotonicClock.

id property

id: str | None

The id the section was stopped under, or None while it runs.

children property

children: tuple[Section, ...]

The sections opened inside this one, in the order they opened.

set_id

set_id(section_id: str) -> Self

Name the section section_id.

get

get(section_id: str) -> Section | None

Return the child named section_id, or None.

open

open(section_id: str | None) -> Section

Return the child named section_id, opening a new one when there is none.

start_event

start_event(name: str, category: str | None) -> StopwatchEvent

Start name here, making the event the first time it is started.

is_event_started

is_event_started(name: str) -> bool

Tell whether name has an open period here.

stop_event

stop_event(name: str) -> StopwatchEvent

Stop name here.

Raises:

lap_event

lap_event(name: str) -> StopwatchEvent

Stop name and start it again at once.

Raises:

get_event

get_event(name: str) -> StopwatchEvent

Return the event name.

Raises:

get_events

get_events() -> dict[str, StopwatchEvent]

Return every event of this section by name, in the order each first started.

Stopwatch

Stopwatch(clock: ClockInterface | None = None)

Times what code does, as named events grouped into sections.

stopwatch = Stopwatch()
stopwatch.open_section()
stopwatch.start("load", "orm")
...
stopwatch.stop("load")
stopwatch.stop_section("request-42")
stopwatch.get_section_events("request-42")["load"].get_duration()

An event is started and stopped by name in the current section; a section opened inside another nests under it, and is stored under the id it is stopped with. Opening a section starts :data:SECTION_EVENT in it and :data:SECTION_CHILD_EVENT in its parent, both stopped as it closes, so a section's own duration is one of its events.

What is timed belongs to the calling context: every concurrent unit of work — every request a server handles at once — sees only its own sections. :meth:reset starts the calling context afresh, which is how a unit of work begins with nothing timed.

Make a stopwatch reading clock.

Parameters:

  • clock (ClockInterface | None, default: None ) –

    What time is read from. None uses a :class:~xtr_clock.MonotonicClock, because a duration must not follow a wall-clock correction.

detached_variable instance-attribute

detached_variable: tuple[ContextVar[_Activity | None], None] = (self._activity, None)

The variable a new connection must start without, and the value it starts from.

A server may start a connection from a copy of another's context taken mid-request; whoever builds the stopwatch for a container registers this, so that request's timing never reaches the new one.

open_section

open_section(section_id: str | None = None) -> None

Open a section inside the current one, or reopen the child named section_id.

Raises:

  • UnknownSectionError –

    When section_id is given and the current section holds no child under it.

stop_section

stop_section(section_id: str) -> None

Close the current section, storing it under section_id.

Raises:

start

start(name: str, category: str | None = None) -> StopwatchEvent

Start the event name in the current section and return it.

Keep the returned event to stop it: it stays the same object even if the context is reset while it runs.

stop

stop(name: str) -> StopwatchEvent

Stop the event name in the current section and return it.

Raises:

lap

lap(name: str) -> StopwatchEvent

Stop the event name and start it again at once.

Raises:

is_started

is_started(name: str) -> bool

Tell whether the event name is running in the current section.

has_open_section

has_open_section() -> bool

Tell whether the calling context has a section open, without starting anything.

A unit of work timing itself opens a section; code that times what it does on a shared stopwatch asks this first, so a context nobody times in — a worker's own loop, a long command — never accumulates events.

get_event

get_event(name: str) -> StopwatchEvent

Return the event name of the current section.

Raises:

get_section_events

get_section_events(section_id: str) -> dict[str, StopwatchEvent]

Return the events of the section stored as section_id; empty when there is none.

get_sections

get_sections() -> dict[str, Section]

Return every stopped section by id, the root included.

reset

reset() -> None

Forget everything the calling context timed, and start it afresh.

Other contexts are left as they are, and an event already handed out stays the object it was, so stopping it still closes its period.

StopwatchEvent

StopwatchEvent(origin: float, category: str | None = None, name: str | None = None, clock: ClockInterface | None = None)

Times one named thing, however many times it runs.

Each :meth:start opens a period and the matching :meth:stop closes it, so a listener called three times is one event with three periods rather than three events. Starts nest: a start while already running opens a second period, and stops close them last-opened first.

Every reading is in milliseconds from :attr:origin — the instant the event's section began — so the events of a section share one axis and can be drawn on one timeline.

Make an event measured from origin.

Parameters:

  • origin (float) –

    The instant readings are measured from, in milliseconds since the epoch.

  • category (str | None, default: None ) –

    What kind of work this is, grouping events on a timeline; "default" when not given.

  • name (str | None, default: None ) –

    What the event is called, for errors and for plain data.

  • clock (ClockInterface | None, default: None ) –

    What time is read from. None uses a :class:~xtr_clock.MonotonicClock, because a duration must not follow a wall-clock correction.

name property

name: str

What the event is called.

category property

category: str

What kind of work the event times.

origin property

origin: float

The instant readings are measured from, in milliseconds since the epoch.

start

start() -> Self

Open a period now.

stop

stop() -> Self

Close the period opened last.

Raises:

lap

lap() -> Self

Close the open period and open the next one at the same instant.

Raises:

is_started

is_started() -> bool

Tell whether a period is open.

ensure_stopped

ensure_stopped() -> None

Close every open period.

get_periods

get_periods() -> tuple[StopwatchPeriod, ...]

Return every closed period, in the order they closed.

get_start_time

get_start_time() -> float

Return when the event first began, in milliseconds from the origin.

The first closed period's start, or the first open one's when none has closed yet; 0.0 for an event that never started.

get_end_time

get_end_time() -> float

Return when the last closed period ended, in milliseconds from the origin.

get_duration

get_duration() -> float

Return the time spent in every period, open ones up to now, in milliseconds.

to_dict

to_dict() -> dict[str, object]

Return the event as plain data, readable once serialised to JSON.

StopwatchPeriod

StopwatchPeriod(start: float, end: float)

One start and the stop that closed it.

Both ends are milliseconds from the origin of the event the period belongs to, so periods of one event — and of every event of one section — line up on the same axis.

Record a period from start to end, both in milliseconds from the origin.

start property

start: float

When the period began, in milliseconds from the origin.

end property

end: float

When the period ended, in milliseconds from the origin.

duration property

duration: float

How long the period lasted, in milliseconds.

to_dict

to_dict() -> dict[str, float]

Return the period as plain data: start, end and duration.