taoyuetao的个人空间 https://blog.eetop.cn/taoyuetao [收藏] [复制] [分享] [RSS]

空间首页 动态 记录 日志 相册 主题 分享 留言板 个人资料

日志

[原创] 有关likely和unlikely

已有 2462 次阅读| 2006-11-1 11:57 |个人分类:【 Linux & GNU 】

天气: 晴朗
心情: 高兴

================================

Author: taoyuetao
Email: tao_yuetao@yahoo.com.cn
Blog: http://www.eetop.cn/blog/?11145

================================

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


点赞

发表评论 评论 (1 个评论)

回复 popsonic 2007-1-30 16:20
这个主要是为了避免过于复杂的分支预测

facelist

您需要登录后才可以评论 登录 | 注册

  • 关注TA
  • 加好友
  • 联系TA
  • 0

    周排名
  • 0

    月排名
  • 0

    总排名
  • 0

    关注
  • 0

    粉丝
  • 0

    好友
  • 0

    获赞
  • 1075

    评论
  • 4435

    访问数
关闭

站长推荐 上一条 /1 下一条

小黑屋| 关于我们| 联系我们| 在线咨询| 隐私声明| EETOP 创芯网
( 京ICP备:10050787号 京公网安备:11010502037710 )

GMT+8, 2024-4-27 11:21 , Processed in 0.040725 second(s), 15 queries , Gzip On, Redis On.

eetop公众号 创芯大讲堂 创芯人才网
返回顶部