0

Would the following code incur a branch misprediction penalty on let say an Intel Core i7?

for(i = 0, count = *ptr; i < count; i++) {
    // do something
}

count can be 0, 1, or 2.

cleong
  • 7,242
  • 4
  • 31
  • 40
  • 1
    Not enough iterations for it to become predictable – nullpotent Sep 22 '12 at 18:52
  • There is so little code there that there's really no point. If you execute this many times in an outer loop, you might want to convince the compiler to unroll the loop (or manually unroll the loop) so that it can use conditional instructions instead. – tc. Sep 22 '12 at 20:37

1 Answers1

0

If count changes randomly, the loop condition cannot be predicted. If it behaves in a certain pattern - lets say 0,1,2,1 repeatedly - it could be perfectly predicted on a core2 or i7. For other patterns it depends.

See The microarchitecture of Intel, AMD and VIA CPUs: An optimization guide for assembly programmers and compiler makers in the chapter "Branch Prediction" for a more detailed explanation.

Gunther Piez
  • 29,760
  • 6
  • 71
  • 103
  • What if the loop is guaranteed to enter at least once? Does that somehow give the branch predictor enough time to recognize the number of iteration is determined by the value of one of the registers? – cleong Sep 25 '12 at 14:48
  • The branch predictor doesn't work that way. It does not inspect the value of registers (yet). – Gunther Piez Sep 25 '12 at 15:13