Source code for bragi_quantum.experiments.utils.timing

# ══════════════════════════════════════════════════════════════════════════
#     ___   ___ ___   _      _   ___
#    / _ \ / __|_  ) | |    /_\ | _ )
#   | (_) | (__ / /  | |__ / _ \| _ \
#    \__\_\\___/___| |____/_/ \_\___/
#
#   QC2 @ CHALMERS CALIBRATION TOOLKIT
#   (c) 2026 Chalmers University of Technology and Project Contributors
# ──────────────────────────────────────────────────────────────────────────
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       https://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
# ──────────────────────────────────────────────────────────────────────────
#   CONTRIBUTORS list:
#
#   Axel Andersson, axean@chalmers.se
#   Yanchen Lin, linya@chalmers.se
#   Matteo Robbiati, robbiati@chalmers.se
# ══════════════════════════════════════════════════════════════════════════


import time
from collections.abc import Callable, Generator
from contextlib import contextmanager
from typing import Any

from bragi_quantum.datalayer.managing.session import ActiveSession
from bragi_quantum.datalayer.managing.time_tracing import (
    TIMING_OTHER,
    TimingTraceCategory,
)
from bragi_quantum.datalayer.utils.logging import logger
from bragi_quantum.datalayer.utils.logging.visuals import log_timing


[docs] @contextmanager def timed( label: str, suffix_fn: Callable[[float], str] | None = None, timing_category: TimingTraceCategory | None = None, timing_trace_args: dict[str, Any] | None = None, ) -> Generator[None, None, None]: """Context manager that logs the wall-clock duration of the wrapped block. Also records this span into the active session's Chrome/Perfetto timing trace (``timing_trace_events.json``), on top of the human-readable log line. Usage:: with timed("Measurement took: "): hardware_agent.run(compiled_schedule) Pass ``suffix_fn`` to append a string computed from the elapsed time:: with timed("Measurement took: ", suffix_fn=lambda d: f" ({d - expected:+.5g} sec)"): thread_lab.join() Pass ``timing_category`` (timing categories defined in :mod:`bragi_quantum.datalayer.managing.time_tracing`) to bucket it under one of the four named categories; defaults to ``TIMING_OTHER`` if not specified. """ timing_category = timing_category if timing_category is not None else TIMING_OTHER _t0 = time.perf_counter() yield elapsed = time.perf_counter() - _t0 log_timing(label, elapsed, suffix_fn(elapsed) if suffix_fn is not None else "") try: collector = ActiveSession.get_timing_trace_collector() if collector is not None: collector.record_span( label.strip().rstrip(":"), timing_category, _t0, elapsed, args=timing_trace_args, ) except Exception as e: logger.warning(f"Could not record timing trace span for {label!r}: {e}")