Something went wrong. Try again.
prefect server in zig
Something went wrong. Try again.
5.6 kB 97 lines
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798#!/usr/bin/env -S uv run --script# /// script# requires-python = ">=3.12"# ///import argparseimport ioimport jsonimport osfrom pathlib import Pathimport randomimport statisticsimport subprocessimport tarfileimport tempfile
parser = argparse.ArgumentParser(description="Compare real SQLite getters, conversion, and list iteration across Git refs.")parser.add_argument("refs", nargs="*")parser.add_argument("--runs", type=int, default=9)parser.add_argument("--seed", type=int, default=20261011)parser.add_argument("--output", type=Path, required=True)parser.add_argument("--prepare-only", action="store_true")parser.add_argument("--prepared", type=Path)args = parser.parse_args()if not args.prepared and not args.refs: parser.error("provide refs or --prepared")repo = Path(subprocess.check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip())env = dict(os.environ, PREFECT_SERVER_DATABASE_SQLALCHEMY_POOL_SIZE="5", PREFECT_SERVER_LOGGING_LEVEL="ERROR")
if args.prepared: manifest = json.loads(args.prepared.read_text())else: root = Path(tempfile.mkdtemp(prefix="prefect-db-benchmark-")) manifest = {"seed": args.seed, "builds": []} for index, ref in enumerate(args.refs): sha = subprocess.check_output(["git", "rev-parse", ref], text=True).strip() checkout = root / str(index) checkout.mkdir() archive = subprocess.check_output(["git", "archive", sha]) with tarfile.open(fileobj=io.BytesIO(archive)) as source: source.extractall(checkout, filter="data") (checkout / "zig-pkg").symlink_to(repo / "zig-pkg", target_is_directory=True) (checkout / "src/db_memory_bench.zig").write_text((repo / "scripts/benchmark-db-memory.zig").read_text()) build = checkout / "build.zig" text = build.read_text() injection = ''' const memory_bench = b.addExecutable(.{ .name = "db-memory-bench", .root_module = b.createModule(.{ .root_source_file = b.path("src/db_memory_bench.zig"), .target = target, .optimize = optimize, .imports = imports, .link_libc = true, }), }); const install_memory_bench = b.addInstallArtifact(memory_bench, .{}); const memory_bench_step = b.step("build-db-memory-benchmark", "Build isolated DB benchmark"); memory_bench_step.dependOn(&install_memory_bench.step);''' assert " // run step" in text build.write_text(text.replace(" // run step", injection + "\n // run step", 1)) result = subprocess.run(["zig", "build", "build-db-memory-benchmark", "-Doptimize=ReleaseFast"], cwd=checkout, env=env, capture_output=True, text=True) (checkout / "build.log").write_text(result.stdout + result.stderr) if result.returncode: raise SystemExit(f"Build failed for {ref}; see {checkout / 'build.log'}") manifest["builds"].append({"ref": ref, "sha": sha, "binary": str(checkout / "zig-out/bin/db-memory-bench")}) prepared = root / "manifest.json" prepared.write_text(json.dumps(manifest, indent=2) + "\n") print(f"Prepared manifest: {prepared}", flush=True) if args.prepare_only: raise SystemExit(0)
records = []rng = random.Random(args.seed)for repetition in range(args.runs): order = list(manifest["builds"]) rng.shuffle(order) for build in order: result = subprocess.run([build["binary"]], env=env, capture_output=True, text=True) if result.returncode: raise SystemExit(f"Benchmark failed for {build['ref']}:\n{result.stdout}{result.stderr}") for line in (result.stdout + result.stderr).splitlines(): if not line.startswith("BENCH\t"): continue _, case, iterations, elapsed, allocations, allocated_bytes, checksum = line.split("\t") n = int(iterations) records.append({"sha": build["sha"], "ref": build["ref"], "case": case, "repetition": repetition, "iterations": n, "ns_per_op": int(elapsed) / n, "allocations_per_op": int(allocations) / n, "bytes_per_op": int(allocated_bytes) / n, "checksum": int(checksum)}) print(f"Finished sample {repetition + 1}/{args.runs} for {build['ref']}", flush=True)summary = []for build in manifest["builds"]: for case in sorted({record["case"] for record in records}): samples = [record for record in records if record["sha"] == build["sha"] and record["case"] == case] if len(samples) != args.runs: raise SystemExit(f"Expected {args.runs} samples for {build['ref']} {case}, got {len(samples)}") summary.append({"ref": build["ref"], "sha": build["sha"], "case": case, "median_ns_per_op": statistics.median(s["ns_per_op"] for s in samples), "min_ns_per_op": min(s["ns_per_op"] for s in samples), "max_ns_per_op": max(s["ns_per_op"] for s in samples), "allocations_per_op": statistics.median(s["allocations_per_op"] for s in samples), "bytes_per_op": statistics.median(s["bytes_per_op"] for s in samples)})args.output.write_text(json.dumps({"seed": args.seed, "runs": args.runs, "zig_version": subprocess.check_output(["zig", "version"], text=True).strip(), "method": "ReleaseFast real in-memory SQLite, 128 flow rows, 100 warmups per case/process, 3000 measured getter/count operations or 300 list operations per sample, randomized ref order per repetition; allocator wrapper counts caller-visible Zig allocations, not SQLite C allocations or backend pool allocations", "builds": manifest["builds"], "summary": summary, "samples": records}, indent=2) + "\n")print(args.output)