# SPDX-License-Identifier: MIT """Measure an instruction's time on the core from ROM, RAM or the cache (rung 3 helper).""" from __future__ import annotations from gsu_python import GSU ROM_ORIGIN = 0x8000 # 00:8000, outside the cache region (CBR = 0) RAM_ORIGIN = 0x0400 # 70:0400 def core_with(code: list[int], where: str, *, clsr: int, cfgr: int, cls=GSU) -> GSU: """A core whose next instruction after the start NOP is ``code[0]``. ``where``: ``rom``, ``ram`` or ``cache`` (uploaded through the window at CBR = 0, lines valid).""" rom = bytearray(0x20000) ram = bytearray(0x10000) tail = [0x01] * 8 + [0x00] # NOPs, then STOP if where == "rom": rom[: len(code) + len(tail)] = bytes(code + tail) start, pbr = ROM_ORIGIN, 0 elif where == "ram": ram[RAM_ORIGIN : RAM_ORIGIN + len(code) + len(tail)] = bytes(code + tail) start, pbr = RAM_ORIGIN, 0x70 else: start, pbr = 0x0000, 0 g = cls(bytes(rom), ram) g.write_io(0x3039, clsr) g.write_io(0x3037, cfgr) g.write_io(0x303A, 0x18) g.write_io(0x3034, pbr) g.write_io(0x3030, 0) # CBR = 0, every line invalid if where == "cache": body = code + tail body += [0] * (-len(body) % 16) for i, value in enumerate(body): g.write_io(0x3100 + i, value) g.write_io(0x301E, start & 0xFF) g.write_io(0x301F, start >> 8) return g def measure( code: list[int], where: str, *, steps: int, skip: int = 0, clsr: int = 0, cfgr: int = 0x80, settle: bool = True, cls=GSU, ) -> int: """GSU cycles of ``steps`` instructions of ``code`` after its first ``skip`` (set-up, not counted). ``settle`` lets every buffer finish before the measured part (the best case); without it the measured part meets whatever the set-up left pending.""" g = core_with(code, where, clsr=clsr, cfgr=cfgr, cls=cls) g.step() # the start's pipeline NOP for _ in range(skip): g.step() if settle: g.clock = max(g.clock, g.rom_ready, g.ram_ready, g.pixel_ready) used = sum(g.step() for _ in range(steps)) return used // (1 if clsr else 2)