Can branch predictors predict perfectly when the number of loop iterations is not constant?

StackOverflow https://stackoverflow.com/questions/12546713

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.

Était-ce utile?

La 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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top