Files
courier-emu/tests/test_interpreter_clock.py
T
Cryan209andClaude Opus 5 7c879876c9 Service the interpreter's devices on a bounded interval, and cut its dispatch cost
The scheduler used to reach the devices through a UC_HOOK_CODE the
interpreter fired on every instruction, which made ordinary ROM execution
cost what a tracing run costs. The deadline moves inside the dispatch loop
instead: `instruction_clock_add` sets a period, and the loop calls out only
when the count reaches it. Crossing into Python is now bounded by that
interval rather than by the guest's instruction rate.

Two costs in the loop itself go with it.

`_fetch` built a `range` per call to read what is almost always one or two
bytes - it is the most called helper here, 6.4M times per 12M instructions -
so both widths are written out and the general loop kept for the 386ex
profile's wider immediates.

The `group` dispatch is a 65-block if/elif chain that was in group-number
order, which is not frequency order: Jcc is 23% of the instructions a boot
executes and sat eleventh, RET nineteenth, CALL twentieth. Measured over 20M
instructions the chain averaged 16.0 comparisons an instruction; reordering
the blocks by that measurement gives 5.6. Each block moved verbatim - they
test exact equality on one local, so the order is free - and the re-emitted
chain was checked to be a permutation of the original.

Together 15.54s to 14.19s over 20M instructions, with byte-identical output
on MAIN_2.3.31, MAIN_2.3.15 and main2205. The chain reorder is worth less
than its comparison count suggests: CPython 3.14 specialises these well, and
the loop prologue, not the chain, is what sets the floor at 294ns for a NOP.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 22:55:11 +12:00

33 lines
764 B
Python

from courier_emu import x86_interpreter as x86
def _cpu(code: bytes):
cpu = x86.Uc(0, 0, profile="186eb")
cpu.mem_map(0, 0x1000)
cpu.mem_write(0, code)
return cpu
def test_instruction_clock_calls_at_bounded_intervals():
cpu = _cpu(b"\x90" * 12)
calls = []
cpu.instruction_clock_add(4, lambda _cpu, total, _user: calls.append(total))
cpu.emu_start(0, 0, count=10)
assert calls == [4, 8]
assert cpu.retired == 10
def test_instruction_clock_can_stop_before_boundary_instruction():
cpu = _cpu(b"\x90" * 12)
def stop(cpu, _total, _user):
cpu.emu_stop()
cpu.instruction_clock_add(4, stop)
cpu.emu_start(0, 0, count=10)
assert cpu.retired == 3
assert cpu.reg_read(x86.UC_X86_REG_IP) == 3