Search code examples
c++cperformancebuilt-in

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


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?


Solution

  • 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.