Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 15 Feb 2004 08:42:31 -0800
From:      Trent Nelson <trent@teleri.net>
To:        freebsd-hackers@freebsd.org
Subject:   Branch prediction
Message-ID:  <20040215164231.GA54709@teleri.net>

next in thread | raw e-mail | index | archive | help

    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.



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20040215164231.GA54709>