"""Bounded Linux/Unix observation of our own parent and one waited child.""" import hashlib import json import platform import resource import subprocess import sys import time from datetime import datetime, timezone from pathlib import Path def usage(who): value = resource.getrusage(who) return {"user_seconds": value.ru_utime, "system_seconds": value.ru_stime} def delta(after, before): return {key: after[key] - before[key] for key in before} def worker(): start_wall, start_cpu = time.perf_counter_ns(), time.process_time_ns() n = 1_000_000 checksum = sum(i * i for i in range(n)) cpu = time.process_time_ns() - start_cpu wall = time.perf_counter_ns() - start_wall if checksum != (n - 1) * n * (2 * n - 1) // 6: raise RuntimeError("work checksum mismatch") return {"iterations": n, "checksum": str(checksum), "inner_elapsed_ns": wall, "inner_process_cpu_ns": cpu} def observe(): children_before = usage(resource.RUSAGE_CHILDREN) self_before = usage(resource.RUSAGE_SELF) wall_before, cpu_before = time.perf_counter_ns(), time.process_time_ns() child = subprocess.run([sys.executable, "-B", str(Path(__file__).resolve()), "--worker"], check=True, capture_output=True, text=True, timeout=15) parent_cpu = time.process_time_ns() - cpu_before elapsed = time.perf_counter_ns() - wall_before self_after = usage(resource.RUSAGE_SELF) children_after = usage(resource.RUSAGE_CHILDREN) return {"parent_elapsed_ns": elapsed, "parent_process_cpu_ns": parent_cpu, "parent_rusage_before": self_before, "parent_rusage_after": self_after, "parent_rusage_delta": delta(self_after, self_before), "waited_children_before": children_before, "waited_children_after": children_after, "waited_children_delta": delta(children_after, children_before), "worker": json.loads(child.stdout)} def main(): if sys.argv[1:] == ["--worker"]: print(json.dumps(worker())) return if sys.argv[1:]: raise SystemExit("usage: probe_cpu_scope.py [--worker]") observations = [observe() for _ in range(3)] print(json.dumps({ "kind": "native-api-observation", "schema_version": 1, "observed_at": datetime.now(timezone.utc).isoformat(), "python": platform.python_version(), "system": platform.system(), "kernel": platform.release(), "machine": platform.machine(), "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "clock_info": {name: vars(time.get_clock_info(name)) for name in ("perf_counter", "process_time")}, "observations": observations, "limits": "Three local accounting observations, not a cache benchmark or paper replication. Parent clocks bracket spawn/wait; child inner clocks exclude interpreter startup/exit. Waited-child rusage includes child lifetime and has different read boundaries/resolution. Values need not match or reproduce exactly. No other children are created by this probe; unrelated reaping in a general harness would contaminate its aggregate child delta. CPU seconds are not energy.", }, indent=2)) if __name__ == "__main__": main()