// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! How fast the processor runs, in instructions a second. //! //! The number to watch is the throughput, not the wall clock: the emulated //! machine runs at about a megahertz and an instruction takes it two to seven //! cycles, so anything above roughly half a million instructions a second is //! faster than the hardware. Headroom above that is what pays for whatever //! gets emulated next. const std = @import("std"); const zig65 = @import("zig65"); const clock: std.Io.Clock = .awake; /// A mix of what programs actually do: registers, immediate operands, an /// absolute read and write, arithmetic, and a branch back. const program = [_]u8{ 0xa9, 0x00, // LDA #$00 0xaa, // TAX 0xe8, // INX 0x8d, 0x00, 0x30, // STA $3000 0xad, 0x00, 0x30, // LDA $3000 0x69, 0x01, // ADC #$01 0x4c, 0x03, 0x02, // JMP $0203 }; /// Where the loop restarts, which is the INX rather than the top. const loop_entry = 0x0203; /// Not inlined, so that the three processors do not all live in one stack /// frame at once. Three of them together is about three hundred kilobytes, and /// setting them up swamped the measurement. noinline fn run(comptime Model: fn (type) type, name: []const u8, io: std.Io, instructions: usize) !void { const CPU = zig65.CPU(zig65.clock.FakeClock, Model); var cpu: CPU = undefined; try cpu.init(null, null); defer cpu.deinit(); try cpu.memory.loadProgram(0x0200, &program); cpu.program_counter.value = 0x0200; const started: std.Io.Timestamp = .now(io, clock); var done: usize = 0; while (done < instructions) : (done += 1) { cpu.executeInstruction() catch { cpu.program_counter.value = loop_entry; }; } const finished: std.Io.Timestamp = .now(io, clock); const nanoseconds: u64 = @intCast(finished.nanoseconds - started.nanoseconds); const per_second = @as(f64, @floatFromInt(instructions)) / (@as(f64, @floatFromInt(nanoseconds)) / std.time.ns_per_s); const cycles_per_second = @as(f64, @floatFromInt(cpu.clock.cycles)) / (@as(f64, @floatFromInt(nanoseconds)) / std.time.ns_per_s); std.debug.print("{s: <12} {d: >8.1}M instructions/s {d: >8.1}MHz emulated ({d:.0}x a real machine)\n", .{ name, per_second / 1_000_000.0, cycles_per_second / 1_000_000.0, cycles_per_second / 1_020_500.0, }); } /// Times each opcode on its own, by putting it at a fixed address with zeroed /// operands and running it over and over. The absolute numbers include the /// cost of resetting the program counter each time, but that is the same for /// every opcode, so what they are good for is comparing one against another. fn perOpcode(io: std.Io, each: usize) ![256]f64 { const CPU = zig65.Bare; var nanoseconds: [256]f64 = undefined; for (0..256) |opcode| { var cpu: CPU = undefined; try cpu.init(null, null); defer cpu.deinit(); try cpu.memory.loadProgram(0x0200, &[_]u8{ @intCast(opcode), 0x00, 0x02 }); const started: std.Io.Timestamp = .now(io, clock); for (0..each) |_| { cpu.program_counter.value = 0x0200; cpu.executeInstruction() catch {}; } const finished: std.Io.Timestamp = .now(io, clock); nanoseconds[opcode] = @as(f64, @floatFromInt(finished.nanoseconds - started.nanoseconds)) / @as(f64, @floatFromInt(each)); } return nanoseconds; } /// What each opcode is, for grouping the timings into something readable. fn describe(opcode: u8) struct { mnemonic: []const u8, mode: []const u8, documented: bool } { const CPU = zig65.Bare; const data = CPU.Opcodes.get(opcode).?; return .{ .mnemonic = data.mnemonic, .mode = @tagName(data.addressing_mode), .documented = !undocumented(data.mnemonic), }; } fn undocumented(mnemonic: []const u8) bool { const names = [_][]const u8{ "JAM", "SLO", "RLA", "SRE", "RRA", "SAX", "LAX", "DCP", "ISC", "ANC", "ALR", "ARR", "ANE", "LXA", "LAS", "SBX", "SHA", "SHX", "SHY", "TAS", }; for (names) |name| if (std.mem.eql(u8, name, mnemonic)) return true; return false; } /// Times one instruction with the machine put in a particular state first. fn timed( comptime Model: fn (type) type, io: std.Io, each: usize, code: []const u8, setup: fn (cpu: anytype) void, ) !f64 { const CPU = zig65.CPU(zig65.clock.FakeClock, Model); var cpu: CPU = undefined; try cpu.init(null, null); defer cpu.deinit(); try cpu.memory.loadProgram(0x0200, code); setup(&cpu); const started: std.Io.Timestamp = .now(io, clock); for (0..each) |_| { cpu.program_counter.value = 0x0200; cpu.executeInstruction() catch {}; } const finished: std.Io.Timestamp = .now(io, clock); return @as(f64, @floatFromInt(finished.nanoseconds - started.nanoseconds)) / @as(f64, @floatFromInt(each)); } fn binary(cpu: anytype) void { cpu.flags.clear(.D); } fn decimal(cpu: anytype) void { cpu.flags.set(.D); } fn nothing(cpu: anytype) void { _ = cpu; } pub fn main(init: std.process.Init) !void { const instructions: usize = 50_000_000; try run(zig65.memory.Flat(.{}), "flat", init.io, instructions); try run(zig65.memory.AppleIIPlus(.{}), "apple ii+", init.io, instructions); try run(zig65.memory.AppleIIe(.{}), "apple //e", init.io, instructions); // What keeping the record costs, since the corpus pays it. try run(zig65.memory.Flat(.{ .bus_log = true }), "flat +bus", init.io, instructions); std.debug.print("\nper opcode, nanoseconds each:\n", .{}); const each = try perOpcode(init.io, 200_000); // The slowest, which is where anything worth fixing will be. var order: [256]u8 = undefined; for (&order, 0..) |*o, i| o.* = @intCast(i); std.mem.sort(u8, &order, &each, struct { fn gt(ns: *const [256]f64, a: u8, b: u8) bool { return ns[a] > ns[b]; } }.gt); std.debug.print(" slowest:\n", .{}); for (order[0..12]) |opcode| { const d = describe(opcode); std.debug.print(" ${x:0>2} {s: <4} {s: <16} {d: >6.1}ns{s}\n", .{ opcode, d.mnemonic, d.mode, each[opcode], if (d.documented) "" else " (undocumented)", }); } std.debug.print(" fastest:\n", .{}); for (order[244..]) |opcode| { const d = describe(opcode); std.debug.print(" ${x:0>2} {s: <4} {s: <16} {d: >6.1}ns\n", .{ opcode, d.mnemonic, d.mode, each[opcode], }); } // And the same thing grouped, which says whether a whole addressing mode // is slow rather than one instruction. // Two things worth asking about directly. std.debug.print("\n decimal mode, which does the addition a nibble at a time:\n", .{}); const adc = [_]u8{ 0x69, 0x09 }; // ADC #$09 const sbc = [_]u8{ 0xe9, 0x09 }; // SBC #$09 std.debug.print(" ADC binary {d: >6.1}ns ADC decimal {d: >6.1}ns\n", .{ try timed(zig65.memory.Flat(.{}), init.io, 2_000_000, &adc, binary), try timed(zig65.memory.Flat(.{}), init.io, 2_000_000, &adc, decimal), }); std.debug.print(" SBC binary {d: >6.1}ns SBC decimal {d: >6.1}ns\n", .{ try timed(zig65.memory.Flat(.{}), init.io, 2_000_000, &sbc, binary), try timed(zig65.memory.Flat(.{}), init.io, 2_000_000, &sbc, decimal), }); std.debug.print(" the IIe, reading RAM against reading a soft switch:\n", .{}); const ram = [_]u8{ 0xad, 0x00, 0x30 }; // LDA $3000 const switches = [_]u8{ 0xad, 0x10, 0xc0 }; // LDA $c010 const card = [_]u8{ 0xad, 0x00, 0xd0 }; // LDA $d000, which is ROM or the card std.debug.print(" LDA RAM {d: >6.1}ns LDA $c010 {d: >6.1}ns LDA $d000 {d: >6.1}ns\n", .{ try timed(zig65.memory.AppleIIe(.{}), init.io, 2_000_000, &ram, nothing), try timed(zig65.memory.AppleIIe(.{}), init.io, 2_000_000, &switches, nothing), try timed(zig65.memory.AppleIIe(.{}), init.io, 2_000_000, &card, nothing), }); std.debug.print(" the same two from the per-opcode run, as a cross-check:\n", .{}); std.debug.print(" $69 ADC # {d: >6.1}ns $e9 SBC # {d: >6.1}ns\n", .{ each[0x69], each[0xe9] }); std.debug.print(" by addressing mode:\n", .{}); var modes: [12][]const u8 = undefined; var totals: [12]f64 = @splat(0); var counts: [12]usize = @splat(0); var seen: usize = 0; for (0..256) |i| { const d = describe(@intCast(i)); const at = found: { for (modes[0..seen], 0..) |m, k| if (std.mem.eql(u8, m, d.mode)) break :found k; modes[seen] = d.mode; seen += 1; break :found seen - 1; }; totals[at] += each[i]; counts[at] += 1; } for (0..seen) |k| { std.debug.print(" {s: <18} {d: >6.1}ns over {d: >3}\n", .{ modes[k], totals[k] / @as(f64, @floatFromInt(counts[k])), counts[k], }); } }