|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import os |
| 4 | + |
| 5 | +from typing import TYPE_CHECKING |
| 6 | + |
| 7 | +if TYPE_CHECKING: |
| 8 | + from .dist_instrument_hooks import lib as LibType |
| 9 | + |
| 10 | +class InstrumentHooks: |
| 11 | + """Zig library wrapper class providing benchmark measurement functionality.""" |
| 12 | + |
| 13 | + lib: LibType | None |
| 14 | + instance: int | None |
| 15 | + |
| 16 | + def __init__(self) -> None: |
| 17 | + try: |
| 18 | + from .dist_instrument_hooks import lib # type: ignore |
| 19 | + |
| 20 | + instance = lib.instrument_hooks_init(); |
| 21 | + if instance == 0: |
| 22 | + raise RuntimeError("Failed to initialize instrumentation library") |
| 23 | + |
| 24 | + self.instance = instance |
| 25 | + self.lib = lib |
| 26 | + except Exception: |
| 27 | + self.lib = None |
| 28 | + self.instance = None |
| 29 | + |
| 30 | + def __del__(self): |
| 31 | + if self.lib is None: |
| 32 | + return |
| 33 | + |
| 34 | + self.lib.instrument_hooks_deinit(self.instance); |
| 35 | + |
| 36 | + def start_benchmark(self) -> None: |
| 37 | + """Start a new benchmark measurement.""" |
| 38 | + if self.lib is None: |
| 39 | + return |
| 40 | + |
| 41 | + self.lib.instrument_hooks_start_benchmark(self.instance) |
| 42 | + |
| 43 | + def stop_benchmark(self) -> None: |
| 44 | + """Stop the current benchmark measurement.""" |
| 45 | + if self.lib is None: |
| 46 | + return |
| 47 | + |
| 48 | + self.lib.instrument_hooks_stop_benchmark(self.instance) |
| 49 | + |
| 50 | + def set_current_benchmark(self, uri: str, pid: int | None = None) -> None: |
| 51 | + """Set the current benchmark URI and process ID. |
| 52 | +
|
| 53 | + Args: |
| 54 | + uri: The benchmark URI string identifier |
| 55 | + pid: Optional process ID (defaults to current process) |
| 56 | + """ |
| 57 | + if self.lib is None: |
| 58 | + return |
| 59 | + |
| 60 | + if pid is None: |
| 61 | + pid = os.getpid() |
| 62 | + self.lib.instrument_hooks_current_benchmark(self.instance, pid, uri.encode("ascii")) |
| 63 | + |
| 64 | + def set_integration(self, name: str, version: str) -> None: |
| 65 | + """Set the integration name and version.""" |
| 66 | + if self.lib is None: |
| 67 | + return |
| 68 | + |
| 69 | + self.lib.instrument_hooks_set_integration(self.instance, name.encode("ascii"), version.encode("ascii")) |
| 70 | + |
| 71 | + def is_instrumented(self) -> bool: |
| 72 | + """Check if instrumentation is active.""" |
| 73 | + if self.lib is None: |
| 74 | + return False |
| 75 | + |
| 76 | + return self.lib.instrument_hooks_is_instrumented(self.instance) |
0 commit comments