歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux綜合 >> Linux內核 >> Linux內核中的likely和unlikely詳解

Linux內核中的likely和unlikely詳解

日期:2017/3/1 10:03:33   编辑:Linux內核

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.

Copyright © Linux教程網 All Rights Reserved