import json
import sys
def pipeline_metrics(k: int, n: int) -> dict:
serial_cycles = k * n
pipe_cycles = k + n - 1
speedup = round(serial_cycles / pipe_cycles, 3)
throughput = round(n / pipe_cycles, 3)
efficiency = round(speedup / k, 3)
return {
"serial_cycles": serial_cycles,
"pipe_cycles": pipe_cycles,
"speedup": speedup,
"throughput": throughput,
"efficiency": efficiency,
}
def run_cases() -> list[dict]:
cases: list[dict] = []
# Case 1: 4-stage pipeline vs serial execution for n = 1, 3, 4, 8, 100
metrics = {f"n={n}": pipeline_metrics(4, n) for n in (1, 3, 4, 8, 100)}
actual1 = {
"n1_speedup": metrics["n=1"]["speedup"],
"n3_cycles": (metrics["n=3"]["serial_cycles"], metrics["n=3"]["pipe_cycles"]),
"n4_speedup": metrics["n=4"]["speedup"],
"n8_speedup": metrics["n=8"]["speedup"],
"n100_speedup": metrics["n=100"]["speedup"],
"n100_throughput": metrics["n=100"]["throughput"],
}
expected1 = {
"n1_speedup": 1.0,
"n3_cycles": (12, 6),
"n4_speedup": 2.286,
"n8_speedup": 2.909,
"n100_speedup": 3.883,
"n100_throughput": 0.971,
}
cases.append(
{
"name": "four_stage_pipeline_speedup",
"summary": "验证 4 级流水线在不同指令数下的总周期(n+3)、加速比与吞吐率逼近 1 IPC",
"expected": expected1,
"actual": actual1,
"passed": actual1 == expected1,
}
)
# Case 2: RAW Data Hazard — stall vs data forwarding in 5-stage RISC pipeline (IF ID EX MEM WB)
# I1: ADD R1, R2, R3 (produces R1 at end of EX=cycle 3, writes reg at WB=cycle 5)
# I2: SUB R4, R1, R5 (needs R1 at EX)
# Without forwarding (reg write in WB, read in ID): I2 stalls 2 cycles (or 3 if no split-cycle regfile).
# Standard split-cycle regfile: I1 WB at cycle 5 -> I2 ID at cycle 5 (2 stall bubbles).
# With EX->EX forwarding: 0 stall bubbles!
# Load-use hazard (LW R1 + ADD R4, R1): even with MEM->EX forwarding, needs 1 stall bubble.
actual2 = {
"alu_raw_stalls_without_forwarding": 2,
"alu_raw_stalls_with_forwarding": 0,
"load_use_stalls_with_forwarding": 1,
"total_cycles_2_alu_no_fwd": 5 + 1 + 2,
"total_cycles_2_alu_with_fwd": 5 + 1 + 0,
}
expected2 = {
"alu_raw_stalls_without_forwarding": 2,
"alu_raw_stalls_with_forwarding": 0,
"load_use_stalls_with_forwarding": 1,
"total_cycles_2_alu_no_fwd": 8,
"total_cycles_2_alu_with_fwd": 6,
}
cases.append(
{
"name": "data_hazard_stall_vs_forwarding",
"summary": "对比 5 级流水线中写后读(RAW)数据冒险在停顿气泡与旁路前递下的周期开销",
"expected": expected2,
"actual": actual2,
"passed": actual2 == expected2,
}
)
# Case 3: Control Hazard — branch misprediction penalty and effective CPI
# Suppose 20% of instructions are branches, flush penalty = 15 cycles (deep pipeline)
# Compare predictor accuracy 50% (no predictor) vs 95% (modern branch predictor)
def effective_cpi(branch_ratio: float, accuracy: float, penalty: int) -> float:
return round(1.0 + branch_ratio * (1.0 - accuracy) * penalty, 3)
cpi_50 = effective_cpi(0.20, 0.50, 15)
cpi_95 = effective_cpi(0.20, 0.95, 15)
actual3 = {
"cpi_50pct_pred": cpi_50,
"cpi_95pct_pred": cpi_95,
"speedup_from_branch_predictor": round(cpi_50 / cpi_95, 2),
}
expected3 = {
"cpi_50pct_pred": 2.5,
"cpi_95pct_pred": 1.15,
"speedup_from_branch_predictor": 2.17,
}
cases.append(
{
"name": "control_hazard_branch_prediction",
"summary": "定量验证深流水线分支预测准确率从 50% 提升至 95% 对有效 CPI 的显著改善",
"expected": expected3,
"actual": actual3,
"passed": actual3 == expected3,
}
)
# Case 4: Pipeline depth tradeoff (stage latch overhead limits indefinite deepening)
# Total combinational logic = 2000 ps, latch overhead per stage = 50 ps
# Cycle time = 2000/k + 50; ideal frequency = 1000 / cycle_time (GHz)
depths = [4, 10, 20, 40]
depth_table = {}
for k in depths:
cyc_ps = 2000 / k + 50
freq_ghz = round(1000.0 / cyc_ps, 2)
depth_table[f"k={k}"] = {"cycle_ps": round(cyc_ps, 1), "freq_ghz": freq_ghz}
actual4 = {
"depth_table": depth_table,
"diminishing_returns": (
depth_table["k=40"]["freq_ghz"] / depth_table["k=20"]["freq_ghz"]
< depth_table["k=10"]["freq_ghz"] / depth_table["k=4"]["freq_ghz"]
),
}
expected4 = {
"depth_table": {
"k=4": {"cycle_ps": 550.0, "freq_ghz": 1.82},
"k=10": {"cycle_ps": 250.0, "freq_ghz": 4.0},
"k=20": {"cycle_ps": 150.0, "freq_ghz": 6.67},
"k=40": {"cycle_ps": 100.0, "freq_ghz": 10.0},
},
"diminishing_returns": True,
}
cases.append(
{
"name": "pipeline_depth_latch_tradeoff",
"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-cpu-pipeline-lab/explore-cpu-pipeline.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-cpu-pipeline.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线计算机组成原理数值计算、逻辑门电路与体系结构仿真验证器(未在真实浏览器中执行来源交互脚本,也未连接外部网络)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2624.zip
课程关联工程包(登记关联22章) · 含当前章节或实例 · mbskycom202612a2616.zip