likely && unlikely

likely和unlikely是gcc扩展的跟处理器相关的宏:

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


现在处理器都是流水线的,有些里面有多个逻辑运算单元,系统可以提前取多条指令进行并行处理,但遇到跳转时,则需要重新取指令,这相对于不用重新去指令就降低了速度。所以就引入了likely和unlikely,目的是增加条件分支预测的准确性,cpu会提前装载后面的指令,遇到条件转移指令时会提前预测并装载某个分支的指令。unlikely 表示你可以确认该条件是极少发生的,相反likely表示该条件多数情况下会发生。编译器会产生相应的代码来优化cpu执行效率。
因此程序员在编写代码时可以根据判断条件发生的概率来优化处理器的取指操作。

 从表面上看if(likely(value)) == if(value),if(unlikely(value)) == if(value)

 内核2.2.26的头文件include/linux/compiler.h中有宏定义

/*
 * Generic compiler-dependent macros required for kernel
 * build go below this comment. Actual compiler/compiler version
 * specific implementations come from the above header files
 */

#define likely(x) __builtin_expect(!!(x), 1)
#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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C语言中,UNLIKELY是一个宏定义,用于提示编译器某个条件的发生概率较低。它一般用于if语句中,让编译器优化代码以提高性能。UNLIKELY可以与条件表达式结合使用,以告诉编译器这个条件很少会满足,从而优化代码的执行路径。通常,UNLIKELY用于if语句中的条件表达式,使得编译器更倾向于执行if语句中的else分支,以提高代码的执行效率。!!运算符是C语言中处理逻辑表达式的一个技巧,用于将非零值转换为1。当变量x为非零值时,!!(x)返回1,当x为零时,!!(x)返回0。这个技巧常用于将条件表达式的结果映射为布尔值。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [C语言技巧:有if时使用likelyunlikely让代码运行更快](https://blog.csdn.net/freestep96/article/details/128771498)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [C语言进阶——likelyunlikely](https://blog.csdn.net/weixin_44873133/article/details/107302688)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值