简体   繁体   English

使用__builtin_expect()时“非常有可能”或Linux内核的可能与不可能

[英]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. 如果您的代码“很有可能”遵循预测的分支,则仅应使用__builtin_expect()或Linux内核的likely()unlikely() 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. 我的程序从2个NIC捕获数据包,并将其保存在2个单独的缓冲区中。 I expect after receiving 25 packets from NIC 1, one packets received from NIC2. 我希望从NIC 1收到25个数据包后,从NIC2收到一个数据包。

So, i need to use an if statement like: 因此,我需要使用if语句,例如:

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

So, is this good situation to use __builtin_expect() or the Linux kernel's likely() ? 那么,使用__builtin_expect()或Linux内核的likely()是一种好情况吗? Do this situation satisfies "very likely" condition? 这种情况是否满足“非常可能”的条件?

It is hard to believe there can be a CPU performance bottleneck in the network code. 很难相信网络代码中可能存在CPU性能瓶颈。
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. 即使有进行这种优化的理由,使用配置文件引导(PGO)而不是使用某些特定于平台且难以读取的代码来阻塞源代码也要聪明得多。

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. 如果likely() / unlikely()如果您知道自己的确切目标平台,并且知道某个特定的CPU完全没有分支预测,那么您可以从中做出一些贡献,否则可能会浪费时间。

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. 但是,如果您渴望知道是否存在差异,请遵循以下范例:进行测量,而不只是猜测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM