# z80-python-fast A fast pure-Python Z80 core that does exactly what [z80-python](https://github.com/alewman/z80-python) does. It is a fork: the reference core is the first commit, and every change after it is an optimization, measured, and checked against the reference boundary by boundary. z80-python is written to be read, so it keeps its instructions in decoded families with the manual beside each one. This fork gives that up for speed. The behaviour stays the same, and that is enforced, not assumed. The reference is still the specification, and every handler here names the reference handler it was transcribed from. ## Speed `benchmarks/speed.py` runs both cores on the same workloads through the same public API, alternating, one fresh interpreter per round, and reports each core's best round. It refuses to print a time when the cores end in different states. The machine is a shared i9-13900K; the load average was 40 to 53 during these runs, which moves absolute numbers but not the interleaved ratios. MHz is T-states per second: the clock of a real Z80 that would keep pace. The Mega Drive's Z80 runs at 3.58 MHz. **Recorded games.** Each game is a Mega Drive sound driver's own instruction stream. It is recorded from power-on for 900 frames with `benchmarks/record_megadrive.py` and replayed exactly into each core, and each run must end in the recorded final state. | Workload (instructions) | CPython 3.14.4: reference, fast | ratio | PyPy 7.3.20: reference, fast | ratio | | --- | --- | --- | --- | --- | | Castlevania: Bloodlines (3,955,470) | 12.2 MHz, 22.8 MHz | **1.86x** | 172 MHz, 189 MHz | 1.10x | | Streets of Rage 2 (4,990,395) | 11.6 MHz, 23.3 MHz | **2.01x** | 195 MHz, 261 MHz | 1.34x | | Contra: Hard Corps (4,777,891) | 10.3 MHz, 20.5 MHz | **2.00x** | 191 MHz, 171 MHz | 0.90x | **ZEXALL**, first 16M T-states on CPython and 400M on PyPy: | Entry point | CPython 3.14.4 | PyPy 7.3.20 | | --- | --- | --- | | reference, `step()` | 9.2 MHz | 94 MHz | | fast, `step()` | 17.8 MHz (**1.93x**) | 129 MHz (**1.36x**) | | fast, `run()` in 228-T-state slices | 19.5 MHz (**2.11x**) | 59 MHz (0.62x; see below) | The PyPy game figures are steady state, after four untimed replays. PyPy compiles the fast core's 1,793 handlers more slowly than the reference's families: on its first replay of Contra it took 2.1 s against the reference's 1.6 s, and it is level by the fifth. What this means for a Mega Drive: on CPython, a sound driver's Z80 took about a third of one core in real time and now takes about a sixth. On PyPy, either core leaves the Z80 at a few percent of one core. ## What changed Each row is one commit. [docs/optimization-log.md](docs/optimization-log.md) also lists what was tried and removed because it did not pay. | Commit | Change | Effect on ZEXALL, CPython / PyPy | | --- | --- | --- | | 5f6a881 | `tools/gen_ops.py` generates one function per opcode on each of the seven pages, with the register, pair and condition fields resolved when the file is written. The decoding handler mixins are deleted. | 1.68x / 1.0x | | f4f3cd0 | An `_attention` flag guards `step()`'s lifecycle checks (RESET, NMI, INT, HALT, the EI delay). Without it, `step()` is just the fetch and the call. | 1.98x / 1.36x | | 5cb72b3 | `run(t_states)`: the step loop inside the core, for hosts that can batch | CPython: a further 1.09-1.11x | Tried and not kept: a lazy R counter (0.97x on both), flag lookup tables (0.99-1.01x on CPython, 0.89x on PyPy), and `__slots__` (1.00x). ## Equivalence z80-rust had to prove equivalence through JSON traces piped into the reference's `diff`. Both cores here are Python, so `validation/lockstep.py` runs them side by side in one process. The reference is the pinned `z80_python` install, with its own host and manifest loader. The fast core is built only through the public API. After every boundary the checker compares the T-states, all 28 `CPUState` fields, and every bus access in order. A planted one-bit flag error is reported at the first boundary it affects. | Rung | What | Status at bd0f929 | | --- | --- | --- | | 1 | The 3 example manifests, in lockstep | identical | | 2 | SingleStepTests, 1,604 files, via the suite's vector runner (registers, RAM, port order, bus order, T-states) | pass | | 3 | ZEXDOC and ZEXALL in lockstep, 116 segments of 50M boundaries each (`scripts/rung3.py`) | **not yet run** | | 4 | raxoft z80test 1.2a (`z80full`, `z80memptr`, `z80ccf`) | pass | | 5 | The 10 interrupt scenarios as manifests with events, in lockstep, and the interrupt cross-check | identical, pass | | 6 | FUSE 1.6.0, 1,356 cases | 1,350 pass, 6 pinned xfails (as the reference) | | + | 300 random programs × 20,000 boundaries with random NMI, INT, INT-clear and RESET events, through `step()` and through `run(1)`; `run(n)` against `step()` to the same budget | identical | `scripts/gate.sh REV` runs every rung but 3 on a committed revision in its own worktree. It covers lint, the generated-code drift check, lockstep, and the whole suite on PyPy (5,963 passed, 2 skipped, 7 xfailed at bd0f929), and every commit above passed it. Rung 3 is owed before any tag. Pins: z80-python `b59c80b` (0.4.0 plus RESET clearing I and R, the EI-delay fix, and the access-timing table), trace schema 1, SingleStepTests `ebe1875d48f374bcfd4b505d8eb8ee751568b5f7`, z80test 1.2a, FUSE 1.6.0. **History rewrite (2026-11-19).** z80-python's history, which this fork carries up to its fork point, was rewritten to drop GPL test data and a document that named the author, and this repository's with it (the same removals and the author name). Every hash changed and no tip tree did, so every result here still holds. Hashes written before then are the old ones: z80-python `b62891b` is now `b59c80b`, the fork point `465d30d` is now `560b61c`. The random-program lockstep found two reference bugs, both in `step()`'s EI bookkeeping: `EI; DI` left `ei_delay` at -1, so `capture_state()` raised, and `EI; EI` accepted a pending interrupt directly after the second EI. They are fixed upstream in z80-python PR #18 (merged), and this fork took the fix with the reference re-pinned to `b62891b`. `z80_python_fast.timing` is the reference's access-timing table (z80-python PR #19, issue #16): `instruction_timing(bytes)` gives the T-state offset of each bus access an instruction makes. It is the same generated data and the same checks, the core check running against this core. ## Using it The embedding contract is the reference's, unchanged. So are `step()`, `capture_state()`/`restore_state()`, the lifecycle requests, `Flags`, the debugger, the disassembler and the conformance kit. The package imports as `z80_python_fast`, so it can sit beside the reference, and `import z80_python_fast as z80_python` switches a host over. ```python from z80_python_fast import Z80CPU memory = bytearray(0x10000) cpu = Z80CPU(memory.__getitem__, memory.__setitem__) t_states = cpu.step() ``` One addition: `cpu.run(t_states)` steps until at least that many T-states have elapsed and returns how many did. It is exactly a loop around `step()`, for hosts that deliver interrupts between slices. On CPython it is faster at any slice size. On PyPy each call enters and leaves the JIT's compiled loop, so give it large budgets there. At a scanline (228 T-states) it measured 0.56x of `step()`, and at 100,000 T-states and above about 1.3x. What is not promised: the value of a register seen from inside a bus callback in the middle of an instruction. Handlers keep locals and write registers when the reference would have, or later, and nothing in either core's contract says otherwise. ## Reproducing ```text python -m venv .venv && .venv/bin/pip install -e ".[dev]" .venv/bin/pip install "z80-python @ git+https://github.com/alewman/z80-python@b59c80b88086299f277d4d21d82a09e112acdaaf" # oracle data: python scripts/fetch_test_vectors.py, fetch_z80test.py, fetch_fuse_tests.py, # and the ZEX binaries (docs/validation.md) scripts/gate.sh HEAD taskset -c N .venv/bin/python benchmarks/speed.py --workload zexall --cores reference,fast,fast:run benchmarks/record_megadrive.py --help # to record a game (needs megadrive-python) ``` `--cores fast@REV,fast` measures the working tree against any revision. The inherited documents in `docs/` describe the reference's behaviour, and therefore this core's. `docs/optimization-log.md` and this README are the fork's own. ## License MIT, as the reference.