|
| 1 | +"""Resolve libpython at runtime via sysconfig (mirrors pytest-codspeed's |
| 2 | +approach in instruments/walltime.py), register it for obj-skip via the |
| 3 | +client-request shim, then turn instrumentation on and run a small |
| 4 | +integer workload. |
| 5 | +
|
| 6 | +We pass both the sysconfig path AND its os.path.realpath because |
| 7 | +callgrind stores the realpath in obj_node->name (after symlink |
| 8 | +resolution), and the runtime obj-skip check uses exact strcmp.""" |
| 9 | + |
| 10 | +import ctypes |
| 11 | +import os |
| 12 | +import sys |
| 13 | +import sysconfig |
| 14 | + |
| 15 | + |
| 16 | +def libpython_candidates() -> list[str]: |
| 17 | + ldlibrary = sysconfig.get_config_var("LDLIBRARY") |
| 18 | + libdir = sysconfig.get_config_var("LIBDIR") |
| 19 | + paths: list[str] = [] |
| 20 | + if ldlibrary and libdir: |
| 21 | + paths.append(os.path.join(libdir, ldlibrary)) |
| 22 | + if ldlibrary: |
| 23 | + paths.append(os.path.join(sys.prefix, "lib", ldlibrary)) |
| 24 | + # Add realpath variants so the exact-match obj-skip finds the |
| 25 | + # file under whichever name the loader actually mapped. |
| 26 | + resolved: list[str] = [] |
| 27 | + seen: set[str] = set() |
| 28 | + for p in paths: |
| 29 | + if not p: |
| 30 | + continue |
| 31 | + if p not in seen and os.path.exists(p): |
| 32 | + resolved.append(p) |
| 33 | + seen.add(p) |
| 34 | + try: |
| 35 | + r = os.path.realpath(p) |
| 36 | + except OSError: |
| 37 | + continue |
| 38 | + if r not in seen and os.path.exists(r): |
| 39 | + resolved.append(r) |
| 40 | + seen.add(r) |
| 41 | + return resolved |
| 42 | + |
| 43 | + |
| 44 | +def main() -> None: |
| 45 | + here = os.path.dirname(os.path.abspath(__file__)) |
| 46 | + shim = ctypes.CDLL(os.path.join(here, "runtime_obj_skip_py_shim.so")) |
| 47 | + shim.add_obj_skip.argtypes = [ctypes.c_char_p] |
| 48 | + shim.add_obj_skip.restype = None |
| 49 | + shim.start_instr.argtypes = [] |
| 50 | + shim.start_instr.restype = None |
| 51 | + shim.stop_instr.argtypes = [] |
| 52 | + shim.stop_instr.restype = None |
| 53 | + |
| 54 | + for path in libpython_candidates(): |
| 55 | + shim.add_obj_skip(path.encode()) |
| 56 | + if sys.executable: |
| 57 | + shim.add_obj_skip(sys.executable.encode()) |
| 58 | + real = os.path.realpath(sys.executable) |
| 59 | + if real != sys.executable: |
| 60 | + shim.add_obj_skip(real.encode()) |
| 61 | + |
| 62 | + shim.start_instr() |
| 63 | + acc = 0 |
| 64 | + for i in range(10_000): |
| 65 | + acc = (acc + i * i) ^ (i << 1) |
| 66 | + shim.stop_instr() |
| 67 | + |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + main() |
0 commit comments