How much is "very likely" when using __builtin_expect() or Linux kernel's likely and unlikely

201 views Asked by At

You should only use __builtin_expect() or the Linux kernel's likely() and unlikely() if it's "very likely" that your code will follow the predicted branch. How much is "very likely"?

I am working on a packet sniffer program. My program captures packets from 2 NICs and save them on 2 separated buffers. I expect after receiving 25 packets from NIC 1, one packets received from NIC2.

So, i need to use an if statement like:

if (_received_from_nic1) {
    _Connection_Number++;
} else {
    _Session_Number++;
}

So, is this good situation to use __builtin_expect() or the Linux kernel's likely()? Do this situation satisfies "very likely" condition?

2

There are 2 answers

0
Ap31 On BEST ANSWER

It is hard to believe there can be a CPU performance bottleneck in the network code.
Even if there was, there is no reason for branch predictor to fail here, and branch predictors are really good these days.
And even if there was a reason for this optimization, it would be much smarter to do the profile-guiding (PGO) instead of clogging the source with some platform-specific and hardly readable code.

In general, "helping the compiler" is usually a bad idea. There are a few cases where it can be useful, but it's really hard to come up with those.
In the case of likely()/unlikely() if you know your exact target platform and you know it's some specific CPU with no branch prediction altogether, then perhaps you can make something out of it, otherwise it's probably a waste of time.

0
Jonas On

There is no need for likely/unlikely here. The branch predictor will handle this for you. But if you are keen on knowing if there is a difference, then follow this paradigm: do measurements and do not just guess.