蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线运行 SimpleCPU 四阶段追踪、12 周期串行时间线与 16 位指令位域译码

PYTHONWindows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。explore-instruction-cycle.py
explore-instruction-cycle.py194 行
import json
import sys


class SimpleCPU:
    def __init__(self) -> None:
        self.regs = {"A": 0, "B": 0, "C": 0}
        self.memory: dict[int, object] = {}
        self.pc = 0
        self.ir: tuple | None = None
        self.flags = {"GT": False, "EQ": False}
        self.cycles = 0
        self.executed: list[tuple[int, str]] = []

    def run_program(self, program: list[tuple]) -> list[dict]:
        for i, ins in enumerate(program):
            self.memory[i] = ins
        self.pc = 0
        self.cycles = 0
        self.executed = []
        trace = []
        while True:
            # Stage 1: Fetch
            cur_pc = self.pc
            self.ir = self.memory[cur_pc]
            self.pc += 1
            # Stage 2: Decode
            op = self.ir[0]
            args = self.ir[1:]
            # Stage 3 & 4: Execute + Writeback (4 phases per instruction)
            self.cycles += 4
            self.executed.append((cur_pc, op))
            if op == "LOAD":
                self.regs[args[0]] = int(args[1])
            elif op == "ADD":
                self.regs[args[0]] += int(args[1])
            elif op == "MUL":
                self.regs[args[0]] *= int(args[1])
            elif op == "CMP":
                val = self.regs[args[0]]
                imm = int(args[1])
                self.flags["GT"] = val > imm
                self.flags["EQ"] = val == imm
            elif op == "JGT":
                if self.flags["GT"]:
                    self.pc = int(args[0])
            elif op == "STORE":
                self.memory[int(args[1])] = self.regs[args[0]]
            elif op == "HALT":
                trace.append({"pc": cur_pc, "op": op, "regs": dict(self.regs), "next_pc": self.pc})
                break
            trace.append({"pc": cur_pc, "op": op, "regs": dict(self.regs), "next_pc": self.pc})
        return trace


def run_cases() -> list[dict]:
    cases: list[dict] = []

    # Case 1: Full 4-stage execution of (1 + 2) * 3 = 9 with conditional jump JGT skipping addr 7
    cpu = SimpleCPU()
    program = [
        ("LOAD", "A", 1),     # 0: A = 1
        ("ADD", "A", 2),      # 1: A = 3
        ("MUL", "A", 3),      # 2: A = 9
        ("CMP", "A", 5),      # 3: 9 > 5 -> GT=True
        ("JGT", 6),           # 4: jump to 6 (skip 5)
        ("LOAD", "A", 999),   # 5: skipped!
        ("STORE", "A", 100),  # 6: mem[100] = 9
        ("HALT",),            # 7: halt
    ]
    trace = cpu.run_program(program)
    actual1 = {
        "final_A": cpu.regs["A"],
        "mem_100": cpu.memory[100],
        "executed_pcs": [p for p, _ in cpu.executed],
        "skipped_pc_5": 5 not in [p for p, _ in cpu.executed],
        "total_cycles": cpu.cycles,
    }
    expected1 = {
        "final_A": 9,
        "mem_100": 9,
        "executed_pcs": [0, 1, 2, 3, 4, 6, 7],
        "skipped_pc_5": True,
        "total_cycles": 28,
    }
    cases.append(
        {
            "name": "simple_cpu_four_phase_trace",
            "summary": "验证 SimpleCPU 按取指-译码-执行-写回运行 (1+2)*3=9 并经 JGT 跳过地址 5",
            "expected": expected1,
            "actual": actual1,
            "passed": actual1 == expected1,
        }
    )

    # Case 2: Non-pipelined 3-instruction serial timeline (4 cycles per instruction = 12 cycles)
    stages = ["IF", "ID", "EX", "WB"]
    timeline = []
    cycle = 1
    for instr_idx in range(1, 4):
        for st in stages:
            timeline.append((cycle, f"I{instr_idx}", st))
            cycle += 1
    actual2 = {
        "total_cycles": len(timeline),
        "i1_cycles": [c for c, i, _ in timeline if i == "I1"],
        "i3_wb_cycle": [c for c, i, s in timeline if i == "I3" and s == "WB"][0],
    }
    expected2 = {
        "total_cycles": 12,
        "i1_cycles": [1, 2, 3, 4],
        "i3_wb_cycle": 12,
    }
    cases.append(
        {
            "name": "serial_instruction_cycle_timeline",
            "summary": "验证非流水线顺序执行 3 条四阶段指令共消耗 12 个时钟周期",
            "expected": expected2,
            "actual": actual2,
            "passed": actual2 == expected2,
        }
    )

    # Case 3: 16-bit instruction bit-field decode [4-bit opcode | 4-bit dst | 8-bit imm]
    # Example: opcode=0x1 (ADD), dst=0x2 (R2), imm=0x19 (25) -> 0x1219
    word = (0x1 << 12) | (0x2 << 8) | 0x19
    opcode = (word >> 12) & 0xF
    dst = (word >> 8) & 0xF
    imm = word & 0xFF
    actual3 = {
        "encoded_hex": f"0x{word:04X}",
        "opcode": opcode,
        "dst_reg": f"R{dst}",
        "immediate": imm,
    }
    expected3 = {
        "encoded_hex": "0x1219",
        "opcode": 1,
        "dst_reg": "R2",
        "immediate": 25,
    }
    cases.append(
        {
            "name": "instruction_bitfield_decode",
            "summary": "验证 16 位定长指令字按位掩码拆分操作码、目标寄存器与立即数",
            "expected": expected3,
            "actual": actual3,
            "passed": actual3 == expected3,
        }
    )

    # Case 4: Hardware unit activation matrix per stage
    stage_units = {
        "Fetch": ["PC", "MAR", "Memory", "MDR", "IR"],
        "Decode": ["IR", "CU", "RegisterFile"],
        "Execute": ["ALU", "Flags", "AGU"],
        "WriteBack": ["RegisterFile", "Memory"],
    }
    actual4 = {
        "stage_count": len(stage_units),
        "pc_used_in_fetch": "PC" in stage_units["Fetch"],
        "alu_used_in_execute": "ALU" in stage_units["Execute"],
        "ir_bridges_fetch_and_decode": "IR" in stage_units["Fetch"] and "IR" in stage_units["Decode"],
    }
    expected4 = {
        "stage_count": 4,
        "pc_used_in_fetch": True,
        "alu_used_in_execute": True,
        "ir_bridges_fetch_and_decode": True,
    }
    cases.append(
        {
            "name": "stage_hardware_activation",
            "summary": "核对取指、译码、执行、写回四阶段激活的核心寄存器与功能部件",
            "expected": expected4,
            "actual": actual4,
            "passed": actual4 == expected4,
        }
    )

    return cases


def main() -> None:
    payload = {
        "version": f"CPython {sys.version.split()[0]}",
        "cases": run_cases(),
    }
    print(json.dumps(payload, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。

入口文件:projects/computer-organization-instruction-cycle-lab/explore-instruction-cycle.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-instruction-cycle.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:计算机组成原理

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2628.zip

下载课程关联工程包:计算机组成原理

课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a2616.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习