使用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 (不相等则跳转)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一,apk以进程的形式运行,进程的创建是由zygote。 参考文章《深入理解Dalvik虚拟机- Android应...
    Kevin_Junbaozi阅读 7,941评论 0 12
  • Java byte code 的学习意义 为啥要学java bytecode,这就跟你问我已经会python了为...
    shanggl阅读 5,646评论 0 3
  • 中午请支教吃饭。支教们挑了家威宁最豪华清真饭店,说是要宰我一顿。去饭店的路上支教们说:张芳在这里打工。我有些吃惊:...
    诗坚阅读 2,910评论 0 0
  • 上周办公室如硝烟战场,炮火四起,异常吵杂,在此混沌的环境下连续加班一周,能量槽已严重爆红,亟需告假修养,早晨睡到自...
    岁月翎声阅读 1,397评论 0 0
  • 有没有发现标题好像村上春树的:“当我谈跑步时,我谈些什么”,没错,本来我今天就想写这个文章,刚好也把村上的这篇又看...
    阿东咚咚咚阅读 4,223评论 4 5