使用likely和unlikely 优化程序性能

作用

likely unlikely是为编译器提供对分支优化的提示,基本用于if-else的分支优化场景。if-else在汇编时会将else分支的命令生成跳转语句(jmp),而跳转会影响程序性能,所以如果大部分情况下都是else分支成立的话,程序每次都会执行跳转,从而影响效率,使用likelyunlikely即可以告诉编译器大部分情况下哪个分支更有可能成立,从而将该分支的语句编译到前面,提高运行效率。

实现

likelyunlikely是通过宏定义实现的:

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

GCC文档对__builtin_expect()的解释如下:

-- Built-in Function: long __builtin_expect (long EXP, long C)
     You may use `__builtin_expect' to provide the compiler with branch
     prediction information.  In general, you should prefer to use
     actual profile feedback for this (`-fprofile-arcs'), as
     programmers are notoriously bad at predicting how their programs
     actually perform.  However, there are applications in which this
     data is hard to collect.

     The return value is the value of EXP, which should be an integral
     expression.  The value of C must be a compile-time constant.  The
     semantics of the built-in are that it is expected that EXP == C.
     For example:

          if (__builtin_expect (x, 0))
            foo ();

     would indicate that we do not expect to call `foo', since we
     expect `x' to be zero.  Since you are limited to integral
     expressions for EXP, you should use constructions such as

          if (__builtin_expect (ptr != NULL, 1))
            error ();

     when testing pointer or floating-point values.

使用

举个栗子🌰

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

int main(char *argv[], int argc)
{
   int a;

   /* Get the value from somewhere GCC can't optimize */
   a = atoi (argv[1]);

   if (unlikely (a == 2)) //等同于if(a==2)
      a++;
   else
      a--;

   printf ("%d\n", a);

   return 0;
}

注意,编译时需要加 -O2选项
可以用objdump -S XXX 来查看汇编指令
使用unlikely()时,汇编指令为je(相等则跳转)
而使用likely()时,汇编指令为jne (不相等则跳转)

推荐阅读更多精彩内容

  • 中午请支教吃饭。支教们挑了家威宁最豪华清真饭店,说是要宰我一顿。去饭店的路上支教们说:张芳在这里打工。我有些吃惊:...
    诗坚阅读 91评论 0 0
  • 上周办公室如硝烟战场,炮火四起,异常吵杂,在此混沌的环境下连续加班一周,能量槽已严重爆红,亟需告假修养,早晨睡到自...
    岁月翎声阅读 62评论 0 0
  • 有没有发现标题好像村上春树的:“当我谈跑步时,我谈些什么”,没错,本来我今天就想写这个文章,刚好也把村上的这篇又看...
    阿东咚咚咚阅读 562评论 4 5
  • 人越大越喜欢是家里的饭菜味道,在外累了总想着奔回家。八月中秋团圆夜,最愉快的时光,就是和家人一起聊天,一起烘焙,一...
    梦尝客阅读 145评论 0 0
  • 问题: 什么是响应式网站?--一个网站能够兼容多个终端 优势:更好的用户体验,较低的开发维护成本: 从用户的角度:...
    love2013阅读 185评论 0 0