if-else 分支预测
2017-07-04 08:36
211 查看
关于if-else分支预测Branch_predictor的分析
[cpp] view plain copy print?#ifdef __GNUC__
#define LIKELY(x) (__builtin_expect(!!(x), 1))
#define UNLIKELY(x) (__builtin_expect(!!(x), 0))
#else
#define LIKELY(x) (x)
#define UNLIKELY(x) (x)
#endif
#define LIKELY(x) (__builtin_expect(!!(x), 1))
#define UNLIKELY(x) (__builtin_expect(!!(x), 0))
#else
#define LIKELY(x) (x)
#define UNLIKELY(x) (x)
#endif
有时候,我们在看linux的源码时,会看到如下类似的代码:
[cpp] view plain copy print?if (UNLIKELY(fd < 0)) { /* Do something */ } else { /* Do other something */ }
[cpp] view plain copy print?if (LIKELY(!err)) { /* Do something */ } else { /* Do other something */ }
LIKELY 作用是告诉编译器 x表达式更有可能是真的,也就是有很大的几率是运行if分支的。
UNLIKELY 作用是告诉编译器 x表达式更有可能是假的,也就是有很大的几率是运行else分支的。
这样的好处是如果if-else分支预测正确时,可以大大提高程序运行的效率。
参考网址:https://stackoverflow.com/questions/109710/likely-unlikely-macros-in-the-linux-kernel-how-do-they-work-whats-their
[cpp] view plain copy print?#ifdef __GNUC__
#define LIKELY(x) (__builtin_expect(!!(x), 1))
#define UNLIKELY(x) (__builtin_expect(!!(x), 0))
#else
#define LIKELY(x) (x)
#define UNLIKELY(x) (x)
#endif
#ifdef __GNUC__
#define LIKELY(x) (__builtin_expect(!!(x), 1))
#define UNLIKELY(x) (__builtin_expect(!!(x), 0))
#else
#define LIKELY(x) (x)
#define UNLIKELY(x) (x)
#endif
有时候,我们在看linux的源码时,会看到如下类似的代码:
[cpp] view plain copy print?if (UNLIKELY(fd < 0)) { /* Do something */ } else { /* Do other something */ }
if (UNLIKELY(fd < 0)) { /* Do something */ } else { /* Do other something */ }
[cpp] view plain copy print?if (LIKELY(!err)) { /* Do something */ } else { /* Do other something */ }
if (LIKELY(!err)) { /* Do something */ } else { /* Do other something */ }
LIKELY 作用是告诉编译器 x表达式更有可能是真的,也就是有很大的几率是运行if分支的。
UNLIKELY 作用是告诉编译器 x表达式更有可能是假的,也就是有很大的几率是运行else分支的。
这样的好处是如果if-else分支预测正确时,可以大大提高程序运行的效率。
参考网址:https://stackoverflow.com/questions/109710/likely-unlikely-macros-in-the-linux-kernel-how-do-they-work-whats-their
相关文章推荐
- CPU与代码优化(1):用三元操作符替代if-else以降低CPU分支预测惩罚;函数13倍提速(Unity)。
- 实验三——for 语句及分支结构else-if
- 9.2matlab if-else-end分支结构
- PHP分支控制语句 if...else 和 switch
- Java 分支结构 - if...else/switch
- Java 分支结构 - if...else/switch
- C#分支结构if,if-else,if-else if,switch-case区别
- Java 分支结构 - if...else/switch
- 职责链设计模式解决if else多分支问题
- 分支逻辑的实现:switch....case 与 if...else if.....对比
- 自制编程语言CXScript(三) 如何实现if语句、else语句并实现分支跳转
- 优化技巧:提前if判断帮助CPU分支预测
- Matlab编程与数据类型 -- 多分支条件选择语句if/elseif/…/else/end
- 实验三——for 语句及分支结构else-if
- 实验三——for 语句及分支结构else-if
- 汇编的if else的分支结构
- TP框架中关于if、else 分支结构逻辑错误
- 过多if-else分支的优化
- 为什么使用if else分支语句不好
- 实验三--for语句及分支结构else-if