关于if-else分支预测Branch_predictor的分析
- #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__
有时候,我们在看linux的源码时,会看到如下类似的代码:
- if (UNLIKELY(fd < 0))
- {
- /* Do something */
- }
- else
- {
- /* Do other something */
- }
if (UNLIKELY(fd < 0))
{
/* Do something */
}
else
{
/* Do other something */
}
- 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分支预测正确时,可以大大提高程序运行的效率。