有关likely和unlikely
时间:2009-06-22 来源:skyily
在linux中判断语句经常会看到likely和unlikely,例如: if(likely(value)) == if(value), if(unlikely(value)) == if(value)。
也就是likely和unlikely是一样的,但是实际上执行是不同的,加likely的意识是value的值为真的可能性更大一些,那么执行if的机会大,而unlikely表示value的值为假的可能性大一些,执行else机会大一些。加上这种修饰,编译成二进制代码时likely使得if后面的执行语句紧跟着前面的程序,unlikely使得else后面的语句紧跟着前面的程序,这样就会被cache预读取,增加程序的执行速度,likely和unlikely的实现在 __builtin_expect是gcc的一个预处理命令,其解释如下:
long __builtin_expect (long exp, long c)
(‘-fprofile-arcs’), as programmers are notoriously bad at predicting how their The __builtin_expect is a method that gcc (versions >= 2.96) offer for programmers to indicate branch prediction information to the compiler. The return value of __builtin_expect is the first argument (which could only be an integer) passed to it. To check it out how it could be beneficial, an excerpt from "info gcc" : if (__builtin_expect (x, 0)) foo ();
Based on this information the compiler generates intelligent code, such that the most expected result is favored. |
Let us consider it with a simple example function :
[kedar@ashwamedha ~]$ cat abc.c |
And let us see what happens if we make the "if" block more likely
[kedar@ashwamedha ~]$ cat abc.c |
friends: unlikely is a hint about a boolean expression
unlikely is a hint about a boolean expression |