Some software (often performance-oriented, e.g. Linux kernel, DPDK) has C helpers for influencing branch prediction.
I have an absolutely simple code snippet (suppose I know the percantage of a > b) to represent the problem of conditions nesting and applying likely
/unlikely
when some logic is nested:
bool foo()
{
foo1(1);
foo2(2);
/* if (unlikely(a > b)) */
/* if (a > b)*/
{
puts("Ohhh!!! Rare case");
return true;
}
return false;
}
int main(void)
{
/* if (unlikely(foo())) */
/* if (foo()) */
{
puts("Azaza");
}
}
So which 2 lines should be uncomented for more performance from a theoretical point of view?
Obviously there are 3 ways to assist compilier with branch prediction:
1.
if (unlikely(a > b))
...
if (unlikely(foo()))
2.
if (a > b)
...
if (unlikely(foo()))
3.
if (unlikely(a > b))
...
if (foo())
Which is theoretically the most efficient and why?