"""Reference vs fast: the same workloads on both cores, interleaved in one process. The machine this runs on is shared, and separate runs of one core swing by tens of percent with the load. So the cores run alternately, each round in a fresh interpreter (sharing one PyPy process skews the JIT), pinned to one CPU if you ask (``taskset -c N``), and each is judged by its best round, the one least disturbed by other work; the median is printed beside it so a noisy measurement shows itself. Every core is driven only through the public API -- ``Z80CPU(read_byte, write_byte, *, read_port, write_port)`` and ``step()``, or ``run()`` for a core named ``NAME:run`` -- by the same host, for the same T-state budget, so the ratio is the core's and nothing else. Each round also checks that the two cores finish in the same state after the same T-states: a speedup that changes the answer is not reported. Workloads: * ``zexdoc`` / ``zexall``: the start of each exerciser under a minimal CP/M host (BDOS 2 and 9). This is the instruction mix of a real program, dominated by its CRC loop. * a recorded game, ``NAME`` for ``benchmarks/workloads/NAME.z80rec`` (made by ``benchmarks/record_megadrive.py``): a Mega Drive sound driver's instruction stream, replayed whole; ``--t-states`` does not apply. * ``base``, ``indexed_cb``, ``block_io``: the reference's microbenchmark loops from ``benchmarks/z80_core_benchmark.py``. "MHz" is T-states per second divided by a million: the clock of a real Z80 that would keep pace. The Mega Drive's Z80 runs at 3.58 MHz. """ from __future__ import annotations import argparse import dataclasses import hashlib import json import os import platform import statistics import subprocess import sys import time from dataclasses import dataclass from pathlib import Path import z80_python ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "benchmarks")) from z80_core_benchmark import WORKLOADS as MICRO_WORKLOADS # noqa: E402 REPLAY_DIR = ROOT / "benchmarks" / "workloads" ZEX_DIR = Path(os.environ.get("Z80_PYTHON_ZEX_DIR", ROOT / "tests" / "zex")) def _core(name: str) -> type: """``reference``, ``fast`` (this tree), or ``fast@REV`` (a committed revision). Called only in a worker process, so each round imports exactly one core. """ if name == "reference": return z80_python.Z80CPU if name.startswith("fast@"): rev = name.removeprefix("fast@") tree = ROOT / "benchmarks" / ".revs" / rev if not tree.exists(): tree.mkdir(parents=True) archive = subprocess.run( ["git", "-C", str(ROOT), "archive", rev, "src"], capture_output=True, check=True ).stdout subprocess.run(["tar", "-x", "-C", str(tree)], input=archive, check=True) sys.path.insert(0, str(tree / "src")) elif name != "fast": raise ValueError(f"unknown core {name!r}") import z80_python_fast # which tree it comes from is decided above return z80_python_fast.Z80CPU @dataclass(frozen=True) class Workload: name: str image: bytes load_address: int cpm: bool replay: Path | None = None @dataclass(frozen=True) class Run: seconds: float steps: int | None t_states: int state: tuple def _refuse_port_read(port: int) -> int: raise RuntimeError(f"unexpected port read 0x{port:04X}") # ZEX's BDOS calls (function 2, a character; 9, a '$'-terminated string) go, # as on CP/M, through JP BDOS at 0x0005, whose operand (0x0006) is also the top # of memory ZEX loads SP from. The BDOS at 0xF000 is OUT (0),A; RET, so the # host sees the call in write_port and needs no per-instruction PC check: a host # loop around step() and one around run() then do the same work. Output is # discarded. _JP_BDOS = bytes((0xC3, 0x00, 0xF0)) # JP 0F000h _BDOS = bytes((0xD3, 0x00, 0xC9)) # OUT (0),A; RET # The op codes of benchmarks/record_megadrive.py. STEPS, INT, INT_CLEAR, RESET, RESET_CLEAR, NMI, SET, RESTORE = range(1, 9) _BOOLEANS = {"iff1", "iff2", "halted", "reset_pending", "non_maskable_interrupt_pending"} def _load_recording(path: Path) -> tuple[dict, list[int], bytes]: import gzip from array import array with gzip.open(path, "rb") as data: blob = data.read() size = int.from_bytes(blob[:4], "little") header = json.loads(blob[4 : 4 + size]) at = 4 + size count = int.from_bytes(blob[at : at + 4], "little") ops = array("I") ops.frombytes(blob[at + 4 : at + 4 + 4 * count]) return header, ops.tolist(), blob[at + 4 + 4 * count :] def _state_from(state_type: type, header: dict, values: list[int]) -> object: kwargs = {} for name, value in zip(header["fields"], values, strict=True): if name == "maskable_interrupt_vector": kwargs[name] = None if value == 0x100 else value elif name in _BOOLEANS: kwargs[name] = bool(value) else: kwargs[name] = value return state_type(**kwargs) def _replay(core: type, workload: Workload) -> Run: """Replay a recorded game's Z80 (benchmarks/record_megadrive.py): every read returns the value the game's board returned, so both cores run the driver's exact instruction stream; the host is a Python function per access, as a real board's is.""" header, ops, reads = _load_recording(workload.replay) next_read = iter(reads).__next__ def read_byte(address: int) -> int: return next_read() def write_byte(address: int, value: int) -> None: pass cpu = core(read_byte, write_byte, read_port=read_byte, write_port=write_byte) state_type = type(cpu.capture_state()) cpu.restore_state(_state_from(state_type, header, header["initial"])) registers = header["registers"] step = cpu.step total = steps = 0 i, n = 0, len(ops) started = time.perf_counter() while i < n: code = ops[i] if code == STEPS: count = ops[i + 1] for _ in range(count): total += step() steps += count i += 2 elif code == INT: cpu.request_maskable_interrupt(ops[i + 1]) i += 2 elif code == INT_CLEAR: cpu.clear_maskable_interrupt() i += 1 elif code == RESET: cpu.request_reset() i += 1 elif code == RESET_CLEAR: cpu.clear_reset() i += 1 elif code == NMI: cpu.request_non_maskable_interrupt() i += 1 elif code == SET: name = registers[ops[i + 1]] value = ops[i + 2] setattr(cpu, name, bool(value) if name in _BOOLEANS else value) i += 3 elif code == RESTORE: cpu.restore_state(_state_from(state_type, header, ops[i + 1 : i + 29])) i += 29 else: raise ValueError(f"bad op {code} at {i}") seconds = time.perf_counter() - started state = dataclasses.astuple(cpu.capture_state()) final = dataclasses.astuple(_state_from(state_type, header, header["final"])) if state != final: raise RuntimeError(f"replay of {workload.name} ended in a different state than recorded") try: next_read() except StopIteration: pass else: raise RuntimeError(f"replay of {workload.name} left recorded reads unconsumed") return Run(seconds, steps, total, state) def _run(core: type, workload: Workload, budget: int, entry: str) -> Run: if workload.replay is not None: return _replay(core, workload) """Run ``workload`` until ``budget`` T-states have elapsed, through ``step()`` or through ``run()`` in 228-T-state slices (one Mega Drive scanline of Z80 time). Both stop at the same boundary: the first at or past ``budget``.""" memory = bytearray(0x10000) memory[workload.load_address : workload.load_address + len(workload.image)] = workload.image if workload.cpm: registers: list = [] def bdos(port: int, value: int) -> None: cpu = registers[0] if cpu.c == 9: address = (cpu.d << 8) | cpu.e while memory[address] != 0x24: address = (address + 1) & 0xFFFF elif cpu.c != 2: raise RuntimeError(f"BDOS {cpu.c}") memory[0x0000] = 0x76 # warm boot: HALT (ZEX ends far beyond any budget) memory[0x0005:0x0008] = _JP_BDOS memory[0xF000:0xF003] = _BDOS cpu = core( memory.__getitem__, memory.__setitem__, read_port=_refuse_port_read, write_port=bdos, ) registers.append(cpu) cpu.pc = 0x0100 cpu.sp = 0xF000 else: ports = bytearray(0x10000) for offset in range(0x100): memory[0x5000 + offset] = (offset * 17 + 3) & 0xFF ports[0x2000 + offset] = (offset * 29 + 5) & 0xFF cpu = core( memory.__getitem__, memory.__setitem__, read_port=ports.__getitem__, write_port=ports.__setitem__, ) total = 0 steps = None if entry == "step": step = cpu.step steps = 0 started = time.perf_counter() while total < budget: total += step() steps += 1 else: run = cpu.run started = time.perf_counter() while total < budget: total += run(min(228, budget - total)) seconds = time.perf_counter() - started state = dataclasses.astuple(cpu.capture_state()) return Run(seconds, steps, total, (*state, bytes(memory))) def _workloads(names: list[str]) -> list[Workload]: found = [] for name in names: recording = REPLAY_DIR / f"{name}.z80rec" if recording.exists(): found.append(Workload(name, b"", 0, False, recording)) elif name in ("zexdoc", "zexall"): path = ZEX_DIR / f"{name}.com" found.append(Workload(name, path.read_bytes(), 0x0100, True)) else: micro = {w.name: w for w in MICRO_WORKLOADS}[name] found.append(Workload(name, micro.program, 0x0000, False)) return found def _git_head() -> str: try: return subprocess.run( ["git", "-C", str(ROOT), "describe", "--always", "--dirty", "--exclude", "*"], capture_output=True, text=True, check=True, ).stdout.strip() except (OSError, subprocess.CalledProcessError): return "unknown" def _worker(core_name: str, workload_name: str, budget: int) -> None: """One timed round in this process: warm up, run, print a JSON line.""" workload = _workloads([workload_name])[0] name, _, entry = core_name.partition(":") core = _core(name) entry = entry or "step" pypy = platform.python_implementation() == "PyPy" # Untimed warm-up: imports, table builds, and PyPy's JIT. A replay is short # (a few million instructions), and PyPy compiles the fast core's 1,793 # handlers over its first two or three passes, so on PyPy a replay is run # four times first: the timed round is steady state. The warm-up itself is # a real, one-time cost; docs/optimization-log.md records it. warmups = 4 if pypy and workload.replay is not None else 1 for _ in range(warmups): _run(core, workload, min(budget, 16_000_000 if pypy else 160_000), entry) run = _run(core, workload, budget, entry) digest = hashlib.sha256(repr((run.t_states, run.state)).encode()).hexdigest() record = {"seconds": run.seconds, "t_states": run.t_states, "steps": run.steps} print(json.dumps({**record, "digest": digest})) def _round(core_name: str, workload: str, budget: int) -> dict: """Run one round in a fresh interpreter, so neither core's JIT state or heap is shared with the other's (in one PyPy process, two identical cores measured 12-22% apart).""" output = subprocess.run( [sys.executable, __file__, "--worker", core_name, workload, str(budget)], capture_output=True, text=True, check=True, ).stdout return json.loads(output.strip().splitlines()[-1]) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument( "--workload", action="append", help="zexdoc, zexall, base, indexed_cb, block_io (repeatable; default zexall)", ) parser.add_argument("--t-states", type=int, help="T-states per round") parser.add_argument("--rounds", type=int, default=5) parser.add_argument( "--cores", default="reference,fast", help="comma-separated: reference, fast, fast@REV (a git revision of this repo), each " "optionally :run to drive run() instead of step(); 'fast,fast' is an A/A noise check", ) parser.add_argument("--json", type=Path, help="append one JSON line per workload") parser.add_argument("--worker", nargs=3, help=argparse.SUPPRESS) args = parser.parse_args(argv) if args.worker: _worker(args.worker[0], args.worker[1], int(args.worker[2])) return 0 pypy = platform.python_implementation() == "PyPy" budget = args.t_states or (160_000_000 if pypy else 16_000_000) names = args.cores.split(",") labels = [f"{n}#{i + 1}" if names.count(n) > 1 else n for i, n in enumerate(names)] head = _git_head() print( f"{platform.python_implementation()} {platform.python_version()}, " f"z80-python-fast {head}, reference z80-python {z80_python.__file__}" ) for workload in _workloads(args.workload or ["zexall"]): rounds: dict[str, list[dict]] = {label: [] for label in labels} for _ in range(args.rounds): for label, name in zip(labels, names, strict=True): rounds[label].append(_round(name, workload.name, budget)) if len({r["digest"] for rs in rounds.values() for r in rs}) != 1: print(f"{workload.name}: CORES DISAGREE on final state; no timing reported") return 1 t_states = rounds[labels[0]][0]["t_states"] steps = next((r["steps"] for rs in rounds.values() for r in rs if r["steps"]), None) counted = f"{steps:,} instructions, " if steps else "" print(f"\n{workload.name}: {counted}{t_states:,} T-states per round") best: dict[str, float] = {} for label, rs in rounds.items(): seconds = [r["seconds"] for r in rs] best[label] = min(seconds) rate = f" {steps / best[label] / 1e6:7.2f} M instr/s" if steps else "" print( f" {label:14} best {best[label]:8.3f} s" f" median {statistics.median(seconds):8.3f} s{rate}" f" {t_states / best[label] / 1e6:7.2f} MHz" ) record = { "workload": workload.name, "python": f"{platform.python_implementation()} {platform.python_version()}", "head": head, "steps": steps, "t_states": t_states, "seconds": {label: [r["seconds"] for r in rs] for label, rs in rounds.items()}, } if len(labels) == 2: ratio = best[labels[0]] / best[labels[1]] print(f" {labels[0]} / {labels[1]}: {ratio:.2f}x") record["ratio"] = ratio else: first = labels[0] for label in labels[1:]: print(f" {first} / {label}: {best[first] / best[label]:.2f}x") if args.json: with args.json.open("a", encoding="utf-8") as out: out.write(json.dumps(record) + "\n") return 0 if __name__ == "__main__": raise SystemExit(main())