Ikely () and unlikely () are everywhere in the 2.6 kernel, so why use them? What is the difference between them?
First clear:
if (likely (value)) is equivalent to if (value)
if (likely (a>b)) {
Fun1 ();
if (unlikely (value)) is equivalent to if (value)
That is, likely () and unlikely () are the same from the point of view of reading and comprehension.
The two macros are defined in the kernel as follows:
<linux/compiler>#define likely (x) __builtin_expect (!! (x), 1)#define unlikely (x) __builtin_expect (!! (x), 0)
The __built_expect () function here is the built-in function of the GCC (version >= 2.96), which is provided to the programmer for the purpose of using the "branch transfer" of the letter
The compiler optimizes the code to reduce the performance degradation caused by the instruction jump.
__buildin_expect ((x), 1) means that the value of x is more likely to be true.
__buildin_expect ((x), 0) means that the value of x is more likely to be false.
That is, with likely (), the chance to execute the statement after the if is greater, with the unlikely (), the more the statement after the else is executed. Through this
Way, the compiler will be in the process of compiling, the more likely code is followed by the code behind, thereby reducing the performance of the instruction jump caused by the decline.
Like what:
if (Likely (a>b)) {fun1 ();}
This is where the programmer can determine that a>b is likely to be larger in the program execution process, so likely () is used to tell the compiler to FUN1 () function
Binary code immediately follows the previous program so that the cache can take the binary code of the FUN1 () function to the cache when prefetching the data.
In this way, the cache hit rate is added as well.
Similarly, the role of unlikely () is to tell the compiler that the probability of a<b is very small, so here at compile time, the binary Code of FUN2 () will try to
Do not compile with the front of the piece. we don't have to be confused with likely and unlikely, but we need to know if (likely (A>B)) and if (a>b) in the function
is equivalent to the same if (unlikely (a<b)) and if (a<b) functions. The difference is that they claim that the binary code is inconsistent.
, which we can see from their assembly code. In short, the function of likely and unlikely is to add the cache hit rate and improve the system
Execution speed.
Linux kernel source likely () and unlikely ()