GCC的__builtin_expect有多远? [英] How far does GCC's __builtin_expect go?

查看:144
本文介绍了GCC的__builtin_expect有多远?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在回答另一个问题时,我对此感到好奇。我很清楚,如果(__builtin_expect(!! a,0)){
//不可能的话,

  
} else {
//很可能
}

通过沿着提示处理器/改变汇编代码次序/某种魔术的方式来使相当可能的分支更快(通常)更快。 (如果任何人都可以澄清这种魔法也会很棒)。



但是,这样做是否适用于a)inline ifs,b)变量和c)除0之外的值以及1?即将

  __ builtin_expect(!! a,0)? / *不太可能* /:/ *可能* /; 

  int x = __builtin_expect(t / 10,7); 
if(x == 7){
//很可能
} else {
//不太可能
}

  if(__builtin_expect(a,3) ){
//可能
//呃 - 哦,如果a是2,会发生什么?
} else {
//不太可能
}

影响?所有这一切都取决于架构的目标是什么?

解决方案


)inline ifs,b)变量和c)0和1以外的值?

它适用于表达式上下文,确定分支。



所以,a)是的。 b)否。c)是。


并且所有这些都取决于目标架构吗?


是的!



它利用指令流水线,它允许CPU在当前指令完成之前开始处理即将到来的指令。


(如果有人可以说明这种魔法也会很棒)。

( 分支预测使这个描述复杂化,所以我故意忽略它)

任何类似于if语句的代码都意味着表达式可能导致CPU跳转到不同的在程序中的位置。这些跳转使CPU的指令流水线中的内容无效。


$ b

__ builtin_expect 允许(不保证)gcc尝试组装代码,所以可能方案涉及的跳转次数少于替代方案。


While answering another question I got curious about this. I'm well aware that

if( __builtin_expect( !!a, 0 ) ) {
    // not likely
} else {
    // quite likely
}

will make the "quite likely" branch faster (in general) by doing something along the lines of hinting to the processor / changing the assembly code order / some kind of magic. (if anyone can clarify that magic that would also be great).

But does this work for a) inline ifs, b) variables and c) values other than 0 and 1? i.e. will

__builtin_expect( !!a, 0 ) ? /* unlikely */ : /* likely */;

or

int x = __builtin_expect( t / 10, 7 );
if( x == 7 ) {
    // likely
} else {
    // unlikely
}

or

if( __builtin_expect( a, 3 ) ) {
    // likely
    // uh-oh, what happens if a is 2?
} else {
    // unlikely
}

have any effect? And does all of this depend on the architecture being targeted?

解决方案

But does this work for a) inline ifs, b) variables and c) values other than 0 and 1?

It works for an expression context that is used to determine branching.

So, a) Yes. b) No. c) Yes.

And does all of this depend on the architecture being targeted?

Yep!

It leverages architectures that use instruction pipelining, which allow a CPU to begin working on upcoming instructions before the current instruction has been completed.

(if anyone can clarify that magic that would also be great).

("Branch prediction" complicates this description, so I'm intentionally omitting it)

Any code resembling an if statement implies that an expression may result in the CPU jumping to a different location in the program. These jumps invalidate what's in the CPU's instruction pipeline.

__builtin_expect allows (without guarantee) gcc to try to assemble the code so the likely scenario involves fewer jumps than the alternate.

这篇关于GCC的__builtin_expect有多远?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆