Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top