有关likely和unlikely

原文:http://hi.baidu.com/zjlinus/blog/item/b0f831dd13ac50375882ddac.html

linux中判断语句经常会看到likely和unlikely,例如:

if(likely(value)){

}

else{

}

简单从表面上看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的实现在

include/linux/compiler.h中:

      9 #if __GNUC__ == 2 && __GNUC_MINOR__ < 96
     10 #define __builtin_expect(x, expected_value) (x)
     11 #endif
     12
     13 #define likely(x)   __builtin_expect((x),1)
     14 #define unlikely(x) __builtin_expect((x),0)

__builtin_expect是gcc的一个预处理命令,其解释如下:

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

原文链接: https://blog.csdn.net/dog250/article/details/5302753

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    有关likely和unlikely

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/410729

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月26日 下午12:11
下一篇 2023年4月26日 下午12:11

相关推荐