Boss lesson · Unit 03
The sorted-array mystery
Pipelines, branch prediction and a famous puzzle
What you practise
- Pipelining, branch prediction and mispredictions
- Why summing values above a threshold is faster on sorted data
- Clock speed versus cores
Try a question from this lesson
Pick one
data holds a million random bytes. In a compiled language this loop can run several times faster if data is sorted first, yet it adds the same numbers. Why?
total = 0
for x in data:
if x >= 128:
total += xCorrect answer
The CPU guesses how each if will go; sorted data makes it right
Why
Same loop, same count, same additions. The difference is inside the CPU: it starts on the next instructions before it knows how the if turns out. This lesson explains that gamble.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The pipeline
A CPU works like an assembly line. While one instruction executes (E), the next is being decoded (D) and the one after is being fetched (F). The last stage (W) writes the result.
Each instruction still takes four ticks, but once the line is full, one instruction finishes every tick.
tick 1 2 3 4 5 6
instr 1 F D E W
instr 2 F D E W
instr 3 F D E WConcept
Branch prediction
So the CPU guesses. A branch predictor remembers how each branch went recently and bets it will go the same way.
Right guess: no time lost. Wrong guess (a misprediction): the half-finished instructions are thrown away and the line restarts, costing around 15 cycles.
Concept
Clock speed and cores
Clock speed is how many pipeline ticks happen each second: 3 GHz is three billion.
Clock speeds stopped climbing in the mid-2000s, because faster chips ran too hot. Since then chips have gained more cores instead: several CPUs on one chip. Extra cores only help work that can be split up.
9 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× match the pairs
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.