免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2343 | 回复: 3
打印 上一主题 下一主题

请教likely和unlikely [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-01-04 10:10 |只看该作者 |倒序浏览
#define likely(x)        __builtin_expect(!!(x), 1)
#define unlikely(x)        __builtin_expect(!!(x), 0)

#if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
#define __builtin_expect(exp,c) (exp)
#endif


看了好久没看明白,怎么回事。
likely,unlikely的作用是什么?
那个__builtin_expect的宏定义有什么作用?
为什么  !!(x)   这么用?后面的  1 是干什么的?

论坛徽章:
0
2 [报告]
发表于 2006-01-04 10:20 |只看该作者
__builtin_expect在gcc的info手册中:
-- Built-in Function: 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.

论坛徽章:
0
3 [报告]
发表于 2006-01-04 16:50 |只看该作者
只记得《lkd》一书中说,gcc有内嵌的指令,这些指令可以优化很可能发生的和很不可能发生的条件分支,至于为什么这样,我也不清楚,估计是和编译器相关的东西。

论坛徽章:
0
4 [报告]
发表于 2006-01-04 22:55 |只看该作者
在gcc的内嵌优化指令中,会把最可能发生的事情放到流水线的最前面,而把发生比较少可能性的事情放在比较靠后的位置。大概就是这样子的。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP