7

LIKELY&UNLIKELY 宏提示编译器做分支预测

 3 years ago
source link: https://zhiqiang.org/coding/folly-likely-macro.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

LIKELY&UNLIKELY 宏提示编译器做分支预测

作者: 张志强

, 发表于 2019-12-07

, 共 294 字 , 共阅读 237 次

follyLikely.h文件提供了 LIKELY 和 UNLIKELY 宏,提示编译器在分支预测时选择分支。其实现很简单

#define LIKELY(x) (__builtin_expect((x), 1))
#define UNLIKELY(x) (__builtin_expect((x), 0))

用法如下:

#include <folly/likely.h>

int a = 1;
if (LIKELY(a == 1)) {
    a = 2;
}

if (UNLIKELY(a == 3)) {
    a = 3;
}

只在gcc下适用。

Q. E. D.

avatar-0.jpg

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK