你好,游客 登录 注册 搜索
背景:
阅读新闻

Linux内核中的likely和unlikely详解

[日期:2013-01-12] 来源:Linux社区  作者:ce123 [字体: ]

Kernel version:2.6.14

CPU architecture:ARM920T

GCC version:arm-linux-gcc-3.4.1

看内核时经常遇到if(likely( )){}或是if(unlikely( ))这样的语句,不甚了解,例如(选自kernel/fork.c中copy_process):

 SET_LINKS(p);
 if (unlikely(p->ptrace & PT_PTRACED))
  __ptrace_link(p, current->parent);

下面详细分析一下。

likely() 与 unlikely()是内核中定义的两个宏。位于/include/linux/compiler.h中,具体定义如下:

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

__builtin_expect是GCC(version>=2.9)引进的内建函数,其作用就是帮助编译器判断条件跳转的预期值,避免跳转造成时间乱费,有利于代码优化。查阅GCC手册,发现其定义如下(http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html):

 -- 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.

linux
相关资讯       Linux内核学习  Linux内核分析 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款