The problem:
I\'m trying to figure out how to write a code (C preffered, ASM only if there is no other solution) that would make the branch pred
The easiest way to avoid compiler optimizations is to have void f(void) { }
and void g(void) { }
dummy functions in another Translation Unit, and have link-time optimizations disabled. This will force if (*++p) f(); else g();
to be a real unpredictable branch, assuming that p
points to an array of random booleans (This sidesteps the branch prediction problem inside rand()
- just do that before the measurement)
If a for(;;)
loop gives you problems, just throw in a goto
.
Note that the "loop unrolling trick" in the comment is somewhat misleading. You're essentially creating thousands of branches. Each branch would be individually predicted, except that it's likely none of them will be predicted as the CPU simply cannot hold thousands of distinct predictions. This may or may not be a benefit for your real goal.