Instruction pipelines and branch prediction
Watch instructions overlap in a pipeline and a predictor guess each branch.
Explain it simply
Each row is one instruction, and each box is one stage of its work. Fetch reads the instruction, decode reads its parts, and execute does the math. Here each instruction waits until the one above it is done. So 6 of them take 30 cycles.
6 instruction rows. Each row has 5 stage boxes, and the rows follow one after another for 30 cycles.
The time is the instruction count times the stage count.
Show the code ▾Hide the code ▴ · Try it yourself · Python 3
# The loop: for x in a: if x >= 128: s += x, compiled to 7 instructions.
# A 5-stage pipeline checks each branch in stage 3, so a miss costs 2 cycles.
a = [72, 207, 84, 106, 55, 234, 248, 190, 123, 156, 98, 104, 135, 177, 11, 134] # random
K, PENALTY = 5, 2
predictor = "twobit" # "wait", "nottaken", "onebit" or "twobit"
counters = {} # one counter per branch address
def read(pc):
return counters.get(pc, 1 if predictor == "twobit" else 0)
def guess(pc):
if predictor == "nottaken":
return False
return read(pc) >= 2 if predictor == "twobit" else read(pc) == 1
def learn(pc, taken):
if predictor == "onebit":
counters[pc] = int(taken)
if predictor == "twobit":
counters[pc] = min(3, read(pc) + 1) if taken else max(0, read(pc) - 1)
n = lost = 0
misses = {1: 0, 4: 0}
def branch(pc, taken):
global lost
if predictor == "wait":
lost += PENALTY # fetch waits for the check
return
if guess(pc) != taken:
misses[pc] += 1
lost += PENALTY # the wrong fetches are flushed
learn(pc, taken)
s = 0
for i, x in enumerate(a):
n += 2 # x = a[i]; if x < 128: goto 3
branch(1, x < 128)
if x >= 128:
s += x
n += 1 # s = s + x
n += 2 # i = i + 1; if i < 16: goto 0
branch(4, i + 1 < 16)
n += 2 # out = s; halt
cycles = n + K - 1 + lost
print("misses", misses[1], misses[4]) # 10 2
print("instructions", n, "cycles", cycles) # 74 102
print("CPI", round(cycles / n, 2)) # 1.38
Copy it into a file and run it. Change the predictor or sort a.
Common mix-ups
MYTHA pipeline makes each instruction finish sooner.
FIXEach instruction still takes 5 cycles. The pipeline overlaps them, so one instruction finishes every cycle.
MYTHA 2-bit counter learns any repeating pattern.
FIXOn alternating data, the 2-bit counter misses all 16 data checks: it swings between 1 and 2. Real CPUs add branch history.
Takeaways
- A pipeline overlaps instructions, so one finishes each cycle.
- A branch is checked late, so fetch must wait or guess.
- A wrong guess flushes the pipeline, so predictable data runs faster.