Is there a code that results in 50% branch prediction miss?

前端 未结 3 1821
醉梦人生
醉梦人生 2021-02-04 00:52

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

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-04 01:10

    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.

提交回复
热议问题