Branch prediction
Trent Nelson
trent at teleri.net
Sun Feb 15 08:42:31 PST 2004
For as long as I've been programming, I've always been under the
impression that CPUs will always predict a branch as being false
the first time they come across it.
Many, many years ago, I came across a DEC programming guide that
said the same thing. It suggested using 'do { } while()' over
'while() {}' for loops as this ensured that the loop block was
correctly pre-fetched (rather than whatever followed the loop)
the first time the branch was encountered.
To this day, I still write all my code in this fashion. I was
wondering, have either CPU architectures or compilers improved
over time such that this isn't an issue anymore? Are CPUs able
to intelligently predict a branch the first time they encounter
it? Do compilers re-order blocks to optimise pre-fetching and
minimise branch mis-prediction?
With CPUs like the P4 -- with it's 20-something stage pipeline
-- branch mis-prediction is expensive. I realise certain CPUs
optimise their branch prediction units by maintaining branch
prediction histories, which would help when a branch is encoun-
tered repeatedly, but does the old adage of "always predict
false" still hold true the first time a branch is encountered?
So, writing code such that the "true" branch is intended to be
executed far less than what comes after it; good practice or
pointless habit?
Regards,
Trent.
More information about the freebsd-hackers
mailing list