I have a have a few if statements in a performance critical loop that looks something like this
for(i = 0;;i = (i + 1) % n) {
if (i == 3) {
//...
}
}
This opens up the possibility of branch prediction failure, which will slow my program. Fortunately, I know exactly how frequently the condition will be met, once every n
iterations. (I will leave it as an abstract n
because I have multiple similar conditions where n
is different)
What I want to know is if there is any way to tell the branch predictor that this helpful information I have, or if I just have to hope it can find the pattern.
One solution I have considered is unrolling the loop so there is no branch. This is a fine solution, and what I was planning on using, but it has a few slightly unappealing side effects. In particular, it would break DRY and it would create a larger program size (memory is limited, though not that limited).
Can I tell the branch predictor the pattern I know without unrolling the loop?