linux likely & unlikely 宏

以下内容有些参考自网络,自然也将其学习所得的一点知识奉还给网络。


一 简介

在内核代码中可以看到用到likely 跟 unlikely的宏代码有很多处,这2个宏的目的主要是提高执行速度,在一些对性能要求比较高,而且预定性比较高(大部分情况下你预定的结果跟实际跑的结果是一致的)的场合可以结合if语句使用.

二 实现

宏定义位于include/compiler.h文件中,如下

# define likely(x)	__builtin_expect(!!(x), 1)
# define unlikely(x)	__builtin_expect(!!(x), 0)


先看参数,这里用了2个取反操作!!,目的是为了确保参数被正常转换为bool型的数值(自己可以编写测试一下).

再看__builtin_expect,这是GCC的内置函数:可以看文档对其介绍.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
-- 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.

   简单的意思就是对于long __builtin_expect (long exp, long c)原型

参数exp为任一表达式,c必须为常量值,其意义是在exp==c时,该函数返回非0值,意即希望exp==c
回到likelyunlikelylikely实际是希望表达式x==1,即表达式x成立,并且在代码实际执行中,表达式x在绝大多数情况下是成立的,相反,unlikely是希望表达式在绝大多数情况下不成立,

那他是如何优化的呢?这段代码如下:

   
if (likely(a == 2))
        a++;
else
        a--;

   用这个GCC内置函数编译出来的汇编代码 a++这个操作会紧跟判断语句的后面,这样cpu的预取指令流水线就把其弄到cache,比从内存读速度快多了,另外指令跳转会带来性能下降。


三 应用

这对宏的用法跟普通的if语句一样用行了,但是这对宏是不是可以无现限制无条件的使用?我们来看看外国友人的回答.

You should use it only in cases when the likeliest branch is very very very likely, or when the unlikeliest branch is very very very unlikely.



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值