是否有一个编译器提示GCC强制分支预测总是以一定的方式? [英] Is there a compiler hint for GCC to force branch prediction to always go a certain way?
问题描述
对于Intel架构,有没有办法指示GCC编译器生成始终在我的代码中强制分支预测的代码?英特尔硬件甚至支持这一点吗?其他编译器或硬件如何?
我将在C ++代码中使用它,我知道这种情况我希望运行快,不关心慢下来,
for(;;){
if正常){//如何告诉编译器总是分支预测真实值?
doSomethingNormal();
} else {
exceptionCase();
}
}
作为对Evdzhan Mustafa的一个后续问题,提示只是指定一个提示,第一次处理器遇到指令,所有后续的分支预测,正常运作?
GCC支持函数 __ builtin_expect(long exp,long c)
来提供这种功能。您可以此处查看文档。
其中 exp
是使用的条件, c
是预期值。例如,在你的情况下,你会需要
if(__builtin_expect(normal,1))
由于尴尬的语法,这通常用于定义两个自定义宏,例如
#define likely(x)__builtin_expect(!!(x),1)
#define unlikely(x)__builtin_expect / code>
。
: strong>编译器/ cpu分支预测器可能比你在决定这样的事情更熟练,因此这可能是一个未成熟的微优化
For the Intel architectures, is there a way to instruct the GCC compiler to generate code that always forces branch prediction a particular way in my code? Does the Intel hardware even support this? What about other compilers or hardwares?
I would use this in C++ code where I know the case I wish to run fast and do not care about the slow down when the other branch needs to be taken even when it has recently taken that branch.
for (;;) {
if (normal) { // How to tell compiler to always branch predict true value?
doSomethingNormal();
} else {
exceptionalCase();
}
}
As a follow on question for Evdzhan Mustafa, can the hint just specify a hint for the first time the processor encounters the instruction, all subsequent branch prediction, functioning normally?
解决方案 GCC supports the function __builtin_expect(long exp, long c)
to provide this kind of feature. You can check the documentation here.
Where exp
is the condition used and c
is the expected value. For example in you case you would want
if (__builtin_expect(normal, 1))
Because of the awkward syntax this is usually used by defining two custom macros like
#define likely(x) __builtin_expect (!!(x), 1)
#define unlikely(x) __builtin_expect (!!(x), 0)
just to ease the task.
Mind that:
- this is non standard
- a compiler/cpu branch predictor are likely more skilled than you in deciding such things so this could be a premature micro-optimization
这篇关于是否有一个编译器提示GCC强制分支预测总是以一定的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!