使用Likely()/ Unlikely()预处理器在if-else if链中的宏 [英] Using Likely() / Unlikely() Preprocessor Macros in if-else if chain

查看:282
本文介绍了使用Likely()/ Unlikely()预处理器在if-else if链中的宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有:

  #define likely(x)__builtin_expect((x),1)
# define(x)__builtin_expect((x),0)

if(A)
return true;
else if(B)
return false;
...
else if(Z)
return true;
else
//这将永远不会发生!
raiseError();
return false;

我可以把possible()放在最后一个条件检查如 else if可能(Z))表示最终语句(else)是不太可能没有编译器影响以前检查的分支预测?



基本上,如果有一个带有分支预测器提示的条件语句,GCC会尝试优化整个if-else if块吗?

解决方案

您应该明确这一点:

  if )
return true;
else if(B)
返回true;
...
else if(Y)
return true;
else {
if(likely(Z))
return true;

raiseError();
return false;
}



现在编译器清楚地了解您的意图,不会重新分配其他分支概率。代码的可读性也增加了。



我建议你重写也可能和不可能的方式Linux内核做保护免受沉默的积分cast:

  #define可能x)__builtin_expect(!!(x),1)
#define unlikely(x)__builtin_expect(!!(x),0)

If I have:

#define likely(x)       __builtin_expect((x),1)
#define unlikely(x)     __builtin_expect((x),0)

if (A)
    return true;
else if (B)
    return false;
...
else if (Z)
    return true;
else
    //this will never really happen!!!!
    raiseError();
    return false;

Can I put likely() around the last condition check like else if (likely(Z)) to signify that the final statement (else) is very unlikely WITHOUT the compiler affecting the branch prediction of the previous checks?

Basically, does GCC try to optimize the entire if-else if block if there is a single conditional statement with a branch predictor hint?

解决方案

You shall make this explicit:

if (A)
  return true;
else if (B)
  return true;
...  
else if (Y)
  return true;
else {
  if (likely(Z))
    return true;

  raiseError();
  return false;
}

Now compiler clearly understands your intention and will not reassign other branch probabilities. Also readability of code increased.

P.S. I suggest you to rewrite also likely and unlikely in the way Linux kernel do to protect from silent integral casts:

#define likely(x)      __builtin_expect(!!(x), 1)
#define unlikely(x)    __builtin_expect(!!(x), 0)

这篇关于使用Likely()/ Unlikely()预处理器在if-else if链中的宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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