Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pipelining — How to Make the CPU Faster

Pipelining -- How to Make the CPU Faster

Can the CPU get faster without raising the clock frequency? The answer is yes. Pipelining (Pipeline) is one of the most important methods. This lesson uses Python code and Gantt-chart-style visual output to show how pipelining greatly improves instruction execution efficiency.


A real-life analogy: a car-wash assembly line

Imagine you run a car-wash shop. There are two ways to operate it:

Method 1: one person does it all (no pipeline)

One worker handles all the washing steps for a car from start to finish — rinsing, foaming, scrubbing, and drying. Only after finishing one car can the next begin. Each car takes 40 minutes, so only 1.5 cars can be washed per hour.

Method 2: division of labor on an assembly line (with pipeline)

4 workers each handle one step — rinsing, foaming, scrubbing, and drying. Once the first car enters the rinsing step, the rinse worker can start on the second car while the foam worker foams the first. All four are busy at once, and one car is finished every 10 minutes.

The second method does not make any single step faster (rinsing still takes 10 minutes), but by overlapping steps for different cars, the overall throughput is greatly increased.

This is the core idea of CPU pipelining: let different stages of different instructions overlap.


Serial execution vs pipelined execution

The problem with serial execution

Recall from Lesson 12: every instruction goes through four stages: fetch (IF), decode (ID), execute (EX), and write-back (WB).

In serial execution (no pipeline) mode, the CPU must fully complete all four stages of the current instruction before it can start fetching the next one.



周期:  1    2    3    4    5    6    7    8    9    10   11   12

I1:   [IF] [ID] [EX] [WB]

I2:                      [IF] [ID] [EX] [WB]

I3:                                          [IF] [ID] [EX] [WB]



3 条指令 = 12 个周期

The advantage of pipelined execution

In pipelined execution mode, once instruction I1 finishes the fetch stage (IF), the CPU's fetch unit becomes idle. Rather than leaving it waiting, we immediately start fetching the next instruction I2.

Likewise, when I1 finishes decode (ID) and enters the execute stage, the decode unit starts working on I2 while the fetch unit starts on I3.



周期:  1    2    3    4    5    6    7

I1:   [IF] [ID] [EX] [WB]

I2:        [IF] [ID] [EX] [WB]

I3:             [IF] [ID] [EX] [WB]



3 条指令 = 6 个周期(比串行快了一倍!)

Note the key numbers:

When n is large, the pipeline speedup approaches 4 (the number of pipeline stages).

Pipelining does not make a single instruction execute faster (each still needs 4 cycles), but it greatly increases "throughput" — the number of instructions completed per unit time.


The "hazard" problem of pipelines

Pipelining is good but not free. Three typical "hazards" can stall the pipeline:

Hazard type English Description Real-life analogy
Structural hazard Structural Hazard Two stages compete for the same hardware resource (e.g., both need memory access) The car-wash shop has only one pressure washer; both rinsing and final rinse need it, so they must queue
Data hazard Data Hazard A later instruction depends on the result of an earlier one, but the result has not been written back yet To make braised pork you must cut the meat before putting it in the pot. If the cutter hasn't finished, the cook just has to wait
Control hazard Control Hazard When a jump instruction is encountered, we don't know which instruction to fetch next The menu says "if the guest orders spicy, switch to another recipe." Until the guest decides, the kitchen doesn't know what to prepare

Modern CPUs use various techniques to mitigate these hazards:


Interactive demo: pipeline simulator (Gantt-chart style)

The Python code below simulates instruction execution in both pipelined and non-pipelined modes, printing Gantt-chart-style output so you can visually compare the two.

Example

"""
CPU pipeline simulator (runoob demo)
Comparison: no pipeline (serial) vs pipeline (parallel overlap)
Print the execution timeline of each stage of every instruction in Gantt-chart style
"""

Define the instruction sequence and abbreviations for each stage

INSTRUCTIONS

=

[

"I1"

,

"I2"

,

"I3"

,

"I4"

,

"I5"

,

"I6"

,

"I7"

,

"I8"

]

STAGES

=

[

"IF"

,

"ID"

,

"EX"

,

"WB"

]

 

Fetch, decode, execute, write-back

STAGE_NAMES

=

{

"IF"

:

"Fetch"

,

"ID"

:

"Decode"

,

"EX"

:

"Execute"

,

"WB"

:

"Write-back"

}

def

simulate_serial

(

instructions

,

stages

)

:

   

"""
    No-pipeline mode: each instruction fully completes all 4 stages before the next begins
    Returns: (total cycles, 2D timeline array)
    Timeline format: time_grid[cycle][stage_slot] = name of the instruction currently executing, or None
    """

    num_instr

=

len

(

instructions

)

    num_stages

=

len

(

stages

)

    total_cycles

=

num_instr * num_stages  

n instructions × 4 stages

   

time_grid[cycle][stage_slot] → which instruction at this stage in this cycle

    time_grid

=

[

[

None

for

_

in

range

(

num_instr

)

]

for

_

in

range

(

total_cycles

)

]

   

for

i

,

instr

in

enumerate

(

instructions

)

:

        base_cycle

=

i * num_stages

       

for

s_idx

,

stage

in

enumerate

(

stages

)

:

            cycle

=

base_cycle + s_idx

            time_grid

[

cycle

]

[

i

]

=

f

"{instr}({stage})"

   

return

total_cycles

,

time_grid

def

simulate_pipeline

(

instructions

,

stages

)

:

   

"""
    Pipeline mode: different stages of different instructions can overlap
    Returns: (total cycles, 2D timeline array)
    """

    num_instr

=

len

(

instructions

)

    num_stages

=

len

(

stages

)

   

Total pipeline cycles = number of stages + (number of instructions - 1)

    total_cycles

=

num_stages +

(

num_instr -

1

)

    time_grid

=

[

[

None

for

_

in

range

(

num_instr

)

]

for

_

in

range

(

total_cycles

)

]

   

for

i

,

instr

in

enumerate

(

instructions

)

:

       

Stage s of instruction i executes at cycle (i + s)

       

for

s_idx

,

stage

in

enumerate

(

stages

)

:

            cycle

=

i + s_idx

           

if

cycle

<

total_cycles:

                time_grid

[

cycle

]

[

i

]

=

f

"{instr}({stage})"

   

return

total_cycles

,

time_grid

def

print_gantt

(

instructions

,

stages

,

time_grid

,

total_cycles

,

mode_name

)

:

   

"""Print the timeline in Gantt-chart style"""

    num_instr

=

len

(

instructions

)

   

Header

    header

=

f

"{'Cycle':>4} "

   

for

instr

in

instructions:

        header +

=

f

"  {instr:^10}"

   

print

(

header

)

   

print

(

"-"

(

6

12

)

)

   

for

cycle

in

range

(

total_cycles

)

:

        row

=

f

"{cycle+1:>4}  "

       

for

i

in

range

(

num_instr

)

:

            cell

=

time_grid

[

cycle

]

[

i

]

           

if

cell:

               

Give each stage a different marker

               

if

"(IF)"

in

cell:

                    row +

=

f

"  [\033[94mIF\033[0m]     "

 

Blue

               

elif

"(ID)"

in

cell:

                    row +

=

f

"  [\033[93mID\033[0m]     "

 

Yellow

               

elif

"(EX)"

in

cell:

                    row +

=

f

"  [\033[92mEX\033[0m]     "

 

Green

               

elif

"(WB)"

in

cell:

                    row +

=

f

"  [\033[91mWB\033[0m]     "

 

Red

           

else

:

                row +

=

f

"  {'':10}"

       

print

(

row

)

   

print

(

"-"

(

6

12

)

)

   

print

(

f

"Total cycles: {total_cycles}"

)

   

return

total_cycles

def

print_simple_gantt

(

instructions

,

stages

,

time_grid

,

total_cycles

,

mode_name

)

:

   

"""Simplified Gantt chart (no ANSI colors, compatible with all terminals)"""

    num_instr

=

len

(

instructions

)

   

print

(

f

"\n{'='*70}"

)

   

print

(

f

" {mode_name}"

)

   

print

(

f

"{'='*70}"

)

   

Header

    header

=

f

"{'Cycle':>5} |"

   

for

instr

in

instructions:

        header +

=

f

" {instr:^9} |"

   

print

(

header

)

   

print

(

"-"

(

7

11

)

)

   

for

cycle

in

range

(

total_cycles

)

:

        row

=

f

"  {cycle+1:>3} |"

       

for

i

in

range

(

num_instr

)

:

            cell

=

time_grid

[

cycle

]

[

i

]

           

if

cell:

               

Extract stage markers

               

for

stage

in

stages:

                   

if

f

"({stage})"

in

cell:

                        row +

=

f

"  [{stage}]   |"

                       

break

           

else

:

                row +

=

f

"          |"

       

print

(

row

)

   

print

(

"-"

(

7

11

)

)

   

print

(

f

" Total cycles: {total_cycles}"

)

   

return

total_cycles

def

calculate_metrics

(

serial_cycles

,

pipeline_cycles

,

num_instr

,

num_stages

)

:

   

"""Compute performance metrics"""

    speedup

=

serial_cycles / pipeline_cycles

    ideal_speedup

=

num_stages  

Ideal speedup = number of pipeline stages

   

Throughput: number of instructions completed per cycle

    serial_throughput

=

num_instr / serial_cycles

    pipeline_throughput

=

num_instr / pipeline_cycles

   

Pipeline efficiency

   

Total number of slots occupied by all instructions

    used_slots

=

num_instr * num_stages

    total_slots

=

num_instr * pipeline_cycles

    efficiency

=

(

used_slots / total_slots

)

100

if

total_slots

0

else

0

   

return

{

       

'speedup'

: speedup

,

       

'ideal_speedup'

: ideal_speedup

,

       

'serial_throughput'

: serial_throughput

,

       

'pipeline_throughput'

: pipeline_throughput

,

       

'efficiency'

: efficiency

,

       

'serial_cycles'

: serial_cycles

,

       

'pipeline_cycles'

: pipeline_cycles

,

   

}

===== Main program =====

print

(

"="

70

)

print

(

" CPU pipeline simulator — Gantt-chart comparison (runoob demo)"

)

print

(

"="

70

)

print

(

f

" Instruction sequence: {', '.join(INSTRUCTIONS[:8])}"

)

print

(

f

" Pipeline stages: 4 (IF=Fetch, ID=Decode, EX=Execute, WB=Write-back)"

)

print

(

)

1. No pipeline (serial)

serial_cycles

,

serial_grid

=

simulate_serial

(

INSTRUCTIONS

,

STAGES

)

print_simple_gantt

(

INSTRUCTIONS

,

STAGES

,

serial_grid

,

serial_cycles

,

"Mode A: no pipeline (serial execution)"

)

2. With pipeline

pipeline_cycles

,

pipeline_grid

=

simulate_pipeline

(

INSTRUCTIONS

,

STAGES

)

print_simple_gantt

(

INSTRUCTIONS

,

STAGES

,

pipeline_grid

,

pipeline_cycles

,

"Mode B: with pipeline (4-stage pipeline)"

)

3. Performance comparison

metrics

=

calculate_metrics

(

serial_cycles

,

pipeline_cycles

,

len

(

INSTRUCTIONS

)

,

len

(

STAGES

)

)

print

(

f

"\n{'='*70}"

)

print

(

f

" Performance comparison analysis"

)

print

(

f

"{'='*70}"

)

print

(

f

" Instruction count: {len(INSTRUCTIONS)}"

)

print

(

f

" Pipeline stages: {len(STAGES)}"

)

print

(

f

""

)

print

(

f

" No-pipeline total cycles: {metrics['serial_cycles']} cycles"

)

print

(

f

" Pipeline total cycles: {metrics['pipeline_cycles']} cycles"

)

print

(

f

""

)

print

(

f

" Actual speedup: {metrics['speedup']:.2f}x"

)

print

(

f

" Ideal speedup: {metrics['ideal_speedup']}x (equals number of pipeline stages)"

)

print

(

f

""

)

print

(

f

" Serial throughput: {metrics['serial_throughput']:.3f} instructions/cycle"

)

print

(

f

" Pipeline throughput: {metrics['pipeline_throughput']:.3f} instructions/cycle"

)

print

(

f

" Pipeline efficiency: {metrics['efficiency']:.1f}%"

)

print

(

f

""

)

print

(

f

" Conclusion: with a {len(STAGES)}-stage pipeline, the same 8 instructions"

)

print

(

f

" shrink from {metrics['serial_cycles']} cycles to {metrics['pipeline_cycles']} cycles"

)

print

(

f

" a speedup of {metrics['speedup']:.1f} times!"

)

print

(

f

""

)

print

(

f

" Note: the pipeline has "fill" and "drain" overhead."

)

print

(

f

" In the first {len(STAGES)-1} cycles the pipeline is not full (fill phase),"

)

print

(

f

" and in the last {len(STAGES)-1} cycles the pipeline gradually drains."

)

print

(

f

" The more instructions, the smaller the relative fill/drain overhead,"

)

print

(

f

" and the closer the speedup gets to the ideal {len(STAGES)}x."

)

4. Extended demo: speedup trend for different instruction counts

print

(

f

"\n{'='*70}"

)

print

(

f

" Extended analysis: speedup for different instruction counts"

)

print

(

f

"{'='*70}"

)

print

(

f

" {'Instruction count':>6} | {'Serial cycles':>8} | {'Pipeline cycles':>10} | {'Speedup':>8} | {'Speedup/Ideal':>14}"

)

print

(

f

" {'-'*6}-+-{'-'*8}-+-{'-'*10}-+-{'-'*8}-+-{'-'*14}"

)

for

n

in

[

1

,

2

,

4

,

8

,

16

,

32

,

64

,

128

,

256

]

:

    test_instrs

=

[

f

"I{i}"

for

i

in

range

(

1

,

n+

1

)

]

    s_cycles

,

_

=

simulate_serial

(

test_instrs

,

STAGES

)

    p_cycles

,

_

=

simulate_pipeline

(

test_instrs

,

STAGES

)

    sp

=

s_cycles / p_cycles

    ideal

=

len

(

STAGES

)

    ratio

=

(

sp / ideal

)

100

   

print

(

f

" {n:>6} | {s_cycles:>8} | {p_cycles:>10} | {sp:>7.2f}x | {ratio:>13.1f}%"

)

print

(

)

print

(

f

" Conclusion: the more instructions, the closer the speedup to the ideal {len(STAGES)}x (the number of pipeline stages)."

)

print

(

f

" With only 1 instruction, pipelining gives no speedup at all."

)

print

(

f

" But modern programs usually contain millions of instructions, so pipeline efficiency approaches 100%."

)

Run the code above and you will see:

Interactive demo: pipeline Gantt-chart comparison

Below we use a Chart.js horizontal stacked bar chart to draw a Gantt chart that visually compares **no pipeline (serial)andand pipelined (4-stage)** modes for the stage timing of 4 instructions. Each colored block represents one stage (IF=Fetch, ID=Decode, EX=Execute, WB=Write-back); the x-axis is clock cycles.

Pipeline Gantt-chart comparison (runoob demo)

IF Fetch

ID Decode

EX Execute

WB Write-back

No pipeline (serial execution) — 16 cycles total

With pipeline (4-stage) — 7 cycles total

No-pipeline total cycles

16

Pipeline total cycles

7

Speedup

2.29x

Throughput improvement

129%

Key observations:

No-pipeline mode: each instruction occupies 4 consecutive cycles, fully serial between instructions; 4 instructions take 16 cycles.

Pipelined mode: stages of different instructions overlap; 4 instructions take only 7 cycles (= 4 + (4-1)).

Once the pipeline is "full" (from cycle 4), one instruction completes every cycle — that is why throughput rises sharply.


Comparison of pipeline depths

The number of pipeline "stages" sets the theoretical speedup limit, but more stages also mean more severe hazards:

CPU model Pipeline stages Feature
Classic RISC (e.g., MIPS) 5 stages Simple and efficient, good for teaching. Classic five-stage pipeline: IF, ID, EX, MEM, WB
Intel Pentium 4 (NetBurst) 20~31 stages Very long pipeline chasing high frequency, but a branch misprediction is extremely costly, so it was eventually abandoned
Intel Core series (since 2006) 14~19 stages Shorter pipeline + high IPC, balancing frequency and efficiency
Apple M1 (2020) 8 stages (decode) Very wide architecture (8-issue), low frequency with high IPC, excellent energy efficiency

As you can see, pipeline depth is a trade-off: too many stages makes a single branch misprediction too costly; too few and clock frequency cannot go up.

The mainstream trend in modern CPU design is "wide and shallow" — moderate pipeline depth + very wide issue width (starting multiple instructions per cycle), rather than blindly chasing more stages.