Skip to content

Commit f3ed388

Browse files
art049claude
andcommitted
perf(hooks): bind callgrind start/stop directly to avoid extra frame
Assign callgrind_start_instrumentation and callgrind_stop_instrumentation as instance attributes pointing straight at the native C functions instead of routing through Python wrapper methods. This removes one Python stack frame from the hot path around instrumented code, which matters because Valgrind/callgrind measurements include every frame that's live while instrumentation is on. Co-Authored-By: Claude <noreply@anthropic.com>
1 parent e4a419e commit f3ed388

1 file changed

Lines changed: 11 additions & 9 deletions

File tree

src/pytest_codspeed/instruments/hooks/__init__.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from pytest_codspeed.utils import SUPPORTS_PERF_TRAMPOLINE
1212

1313
if TYPE_CHECKING:
14-
from typing import Any
14+
from typing import Any, Callable
1515

1616
# Feature flags for instrument hooks
1717
FEATURE_DISABLE_CALLGRIND_MARKERS = 0
@@ -22,6 +22,10 @@ class InstrumentHooks:
2222

2323
_module: Any
2424
_instance: Any
25+
# Bound directly to the C functions in __init__ to avoid an extra Python
26+
# stack frame when starting/stopping callgrind instrumentation.
27+
callgrind_start_instrumentation: Callable[[], None]
28+
callgrind_stop_instrumentation: Callable[[], None]
2529

2630
def __init__(self) -> None:
2731
if os.environ.get("CODSPEED_ENV") is None:
@@ -35,6 +39,12 @@ def __init__(self) -> None:
3539
except ImportError as e:
3640
raise RuntimeError(f"Failed to load instrument hooks library: {e}") from e
3741
self._module = dist_instrument_hooks
42+
self.callgrind_start_instrumentation = (
43+
dist_instrument_hooks.callgrind_start_instrumentation
44+
)
45+
self.callgrind_stop_instrumentation = (
46+
dist_instrument_hooks.callgrind_stop_instrumentation
47+
)
3848

3949
self._instance = self._module.instrument_hooks_init()
4050
if self._instance is None:
@@ -87,14 +97,6 @@ def is_instrumented(self) -> bool:
8797
"""Check if simulation is active."""
8898
return self._module.instrument_hooks_is_instrumented(self._instance)
8999

90-
def callgrind_start_instrumentation(self) -> None:
91-
"""Start callgrind instrumentation."""
92-
self._module.callgrind_start_instrumentation()
93-
94-
def callgrind_stop_instrumentation(self) -> None:
95-
"""Stop callgrind instrumentation."""
96-
self._module.callgrind_stop_instrumentation()
97-
98100
def set_feature(self, feature: int, enabled: bool) -> None:
99101
"""Set a feature flag in the instrument hooks library.
100102

0 commit comments

Comments
 (0)