Likely () and unlikely () can be seen everywhere in the 2.6 kernel, so why use them? What's the difference between them?
First, be clear:
if(likely(valueif(value) if(unlikely(valueif(value)
That means likely () and unlikely () are the same from the point of view of reading and Understanding Code!!!
#define likely(x) __builtin_expect((x),1)#define unlikely(x) __builtin_expect((x),0)
__builtin_expect () is provided to the programmer by GCC (version >= 2.96) to provide the "branch transfer" information to the compiler so that the compiler can optimize the code to reduce the performance degradation caused by instruction jumps.
__builtin_expect ((x), 1) indicates that the value of x is more likely to be true;
__builtin_expect ((x), 0) means that the value of x is more likely to be false.
That is, with likely (), the chance to execute a statement after an if is greater, with unlikely (), the chance to execute the statement following else is greater.
For example, the following code, the author thinks that Prev is not equal to next is more likely,
ifnext)) { next->timestamp = now; ...else { ...; }
In this way, the compiler will keep the more likely code up-to-date in the compilation process, thus reducing the performance degradation of the instruction jump.
另外内核2.6.31.5中likely和unlikely还有一种定义:# ifndef likely# define likely(x) (__builtin_constant_p(x) ? !!(x) : __branch_check__(x, 1))# endif# ifndef unlikely# define unlikely(x) (__builtin_constant_p(x) ? !!(x) : __branch_check__(x, 0))# endif
For example (kernel version 2.6.22.6): There is a paragraph in/KERNEL/SHED.C:
if (Likely (!active_balance)) {/* We were Unbalanced, so reset the balancing interval */sd->balance_interval = Sd->min_ Interval;} else {/** If we ' ve begun active balancing, start to back off. this* case could not be covered by the all_pinned logic if there* is only 1 task On the busy Runqueue (because we don ' t call* move_tasks). */if (sd->balance_interval max_interval) Sd->balance_interval *= 2 ;}
During compilation, the contents of {} After if are compiled to the front, and the contents of the {} after else are compiled to the back. The opposite is true if the likely is replaced with unlikely.
In short, likely and unlikely interchange or not will not affect the correctness of the program. However, the efficiency of the program may be affected.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Macro definition parsing of likely and unlikely in Linux kernel