C++ __builtin 函数常用用法、写法与拓展应用
1. 什么是 __builtin
__builtin 通常指编译器内建函数,常见于 GCC 和 Clang。
它们不是 C++ 标准库的一部分,而是编译器直接提供的能力,通常用于:
- 位运算优化
- 分支预测提示
- 内存预取
- 类型判断
- 原子操作
- 栈信息获取
- 浮点与数学加速
这类函数的特点是:
- 写法接近普通函数
- 编译器通常会直接展开为高效机器指令
- 可读性和性能往往比手写位运算更好
- 但可移植性弱,MSVC 不一定支持同名接口
2. 使用前的基本认识
2.1 头文件
大多数 __builtin_xxx 不需要额外头文件,编译器直接识别。
但某些配套能力可能仍会搭配这些头文件使用:
#include <iostream>
#include <cstdint>
#include <cstring>
using namespace std;2.2 编译器兼容性
- GCC:支持大量
__builtin - Clang:大多兼容 GCC 风格
__builtin - MSVC:通常不支持同名写法,往往需要换成
_BitScanForward、__popcnt等内建或平台 API
可以用条件编译做兼容:
#if defined(__GNUC__) || defined(__clang__)
// 使用 __builtin
#endif3. 最常用的位运算类 __builtin
这部分是算法、竞赛、底层开发里最常见的用法。
3.1 __builtin_popcount
作用
统计一个整数二进制表示中 1 的个数。
写法
int __builtin_popcount(unsigned int x);
int __builtin_popcountl(unsigned long x);
int __builtin_popcountll(unsigned long long x);示例
unsigned int x = 13; // 1101
cout << __builtin_popcount(x) << endl; // 3常见应用
- 统计状态压缩中某个状态选了多少位
- 判断奇偶性:
__builtin_popcount(x) & 1 - 枚举子集时统计元素数
拓展应用
// 判断是否是 2 的幂(x > 0)
bool isPowerOfTwo(unsigned int x) {
return x && __builtin_popcount(x) == 1;
}3.2 __builtin_parity
作用
判断二进制中 1 的个数是否为奇数。
返回值:
- 奇数个
1:返回1 - 偶数个
1:返回0
写法
int __builtin_parity(unsigned int x);
int __builtin_parityl(unsigned long x);
int __builtin_parityll(unsigned long long x);示例
cout << __builtin_parity(7) << endl; // 7 = 111, 3 个 1,输出 1拓展应用
- 校验位计算
- 某些异或性质问题
- 位集奇偶校验
3.3 __builtin_ctz
作用
统计从低位开始连续 0 的个数,即末尾 0 的数量。
ctz = count trailing zeros
写法
int __builtin_ctz(unsigned int x);
int __builtin_ctzl(unsigned long x);
int __builtin_ctzll(unsigned long long x);示例
unsigned int x = 40; // 101000
cout << __builtin_ctz(x) << endl; // 3重要注意
x = 0 时结果未定义。
安全写法:
int trailingZeros(unsigned int x) {
return x ? __builtin_ctz(x) : 32;
}拓展应用
1. 快速找到最低位的 1
int pos = __builtin_ctz(x); // 最低位 1 的下标2. 提取 lowbit
unsigned int lowbit = x & -x;也可结合 ctz 使用:
unsigned int lowbit = 1u << __builtin_ctz(x);3. 状态压缩中遍历每一个置位 bit
for (unsigned int s = x; s; s &= (s - 1)) {
int bit = __builtin_ctz(s);
cout << bit << " ";
}3.4 __builtin_clz
作用
统计从高位开始连续 0 的个数。
clz = count leading zeros
写法
int __builtin_clz(unsigned int x);
int __builtin_clzl(unsigned long x);
int __builtin_clzll(unsigned long long x);示例
unsigned int x = 16; // 000...00010000
cout << __builtin_clz(x) << endl;在 32 位 unsigned int 上,16 的前导零通常是 27。
重要注意
x = 0 时结果未定义。
拓展应用
1. 计算最高位 1 的位置
int highestBit(unsigned int x) {
return x ? 31 - __builtin_clz(x) : -1;
}2. 计算不小于 x 的最小 2 的幂
unsigned int ceilPow2(unsigned int x) {
if (x <= 1) return 1;
return 1u << (32 - __builtin_clz(x - 1));
}3. 计算二进制位数
int bitWidth(unsigned int x) {
return x ? 32 - __builtin_clz(x) : 0;
}3.5 __builtin_ffs
作用
返回从低位到高位第一个 1 的位置,位置从 1 开始计数。
如果 x == 0,返回 0。
写法
int __builtin_ffs(int x);
int __builtin_ffsl(long x);
int __builtin_ffsll(long long x);示例
cout << __builtin_ffs(40) << endl; // 40 = 101000,第一个 1 在第 4 位,输出 4和 __builtin_ctz 的区别
__builtin_ctz(x):返回末尾 0 的个数,从0开始思考__builtin_ffs(x):返回第一个 1 的位置,从1开始编号
关系:
if (x != 0) {
__builtin_ffs(x) == __builtin_ctz(x) + 1;
}4. 分支预测优化类
4.1 __builtin_expect
作用
告诉编译器某个条件“更可能”为真还是假,用于优化分支布局。
写法
long __builtin_expect(long expr, long expected);示例
if (__builtin_expect(x == 0, 0)) {
// 小概率事件
}表示:x == 0 大概率为假。
常见宏写法:
#define LIKELY(x) __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)使用示例:
if (LIKELY(n > 0)) {
// 常走路径
} else {
// 冷门路径
}拓展应用
- 高频服务中的热路径优化
- 内核、数据库、网络库中的异常路径标记
- 减少分支预测失败带来的流水线代价
注意
- 它只是“提示”,不是强制
- 乱用可能适得其反
- 应基于真实 profiling 数据,而不是主观猜测
4.2 __builtin_unreachable
作用
告诉编译器这段代码理论上不可能执行到。
写法
void __builtin_unreachable(void);示例
int f(int x) {
if (x == 1) return 10;
if (x == 2) return 20;
__builtin_unreachable();
}拓展应用
switch中处理完整枚举后标记默认分支不可达- 配合断言优化死代码消除
- 自定义“永不返回”的错误处理封装
风险
如果程序实际跑到这里,行为未定义。
所以只能在你能严格证明“绝不可能到达”时使用。
5. 内存与性能优化类
5.1 __builtin_prefetch
作用
预取某段内存到缓存,降低未来访问延迟。
写法
void __builtin_prefetch(const void *addr, int rw = 0, int locality = 3);参数含义:
addr:要预取的地址rw:0表示读,1表示写locality:局部性,0到3,越大表示越可能重复使用
示例
for (int i = 0; i < n; ++i) {
__builtin_prefetch(&a[i + 16], 0, 1);
sum += a[i];
}拓展应用
- 大数组顺序扫描
- 链表、树、图遍历时预取下一节点
- 数据库和搜索引擎的批量访问优化
注意
- 只有在内存访问确实是瓶颈时才可能有效
- 预取距离太近没收益,太远会污染缓存
- 需要测试,不要想当然
5.2 __builtin_memcpy / __builtin_memset
作用
编译器内建版本的内存操作,通常会被优化得更激进。
示例
char src[] = "hello";
char dst[10];
__builtin_memcpy(dst, src, 6);int a[100];
__builtin_memset(a, 0, sizeof(a));说明
很多时候直接写 memcpy、memset 即可,编译器本身就可能替换成内建实现。
手写 __builtin_memcpy 并不一定更优,更多出现在编译器相关代码或底层工程中。
6. 数学与浮点相关
6.1 __builtin_abs
作用
返回绝对值。
int x = -10;
cout << __builtin_abs(x) << endl; // 10不过普通情况下直接使用 std::abs 更符合 C++ 风格。
6.2 __builtin_sqrt / __builtin_sin / __builtin_cos
一些数学函数存在内建版本,但业务代码里通常优先直接使用标准库:
#include <cmath>
cout << sqrt(25.0) << endl;原因:
- 可读性更好
- 可移植性更强
- 编译器常常已经会做内建优化
7. 类型与编译期判断类
7.1 __builtin_types_compatible_p
作用
判断两个类型是否兼容。这个更常见于 GNU C,C++ 中使用相对少。
写法
int __builtin_types_compatible_p(type1, type2);示例
cout << __builtin_types_compatible_p(int, int) << endl; // 1
cout << __builtin_types_compatible_p(int, long) << endl; // 0应用
- 宏中做类型分发
- 底层泛型工具
- 编译期接口约束
在现代 C++ 中,很多场景更适合用:
std::is_sameif constexpr- 模板偏特化
7.2 __builtin_choose_expr
作用
根据编译期常量条件选择表达式。
更偏 GNU 扩展风格,C++ 里不如 if constexpr 常用。
示例
// GNU 扩展风格示意
// __builtin_choose_expr(cond, expr1, expr2)现代 C++ 更推荐:
if constexpr (sizeof(T) == 4) {
// ...
} else {
// ...
}8. 原子与并发相关
GCC 早期提供过一组原子内建函数:
__sync_fetch_and_add__sync_bool_compare_and_swap__sync_lock_test_and_set
后来又提供更现代的:
__atomic_load_n__atomic_store_n__atomic_fetch_add__atomic_compare_exchange_n
8.1 __sync_fetch_and_add
作用
原子加,并返回加之前的旧值。
示例
volatile int counter = 0;
int old = __sync_fetch_and_add(&counter, 1);应用
- 无锁计数器
- 并发统计
- 简单原子更新
8.2 __atomic_fetch_add
写法
type __atomic_fetch_add(type *ptr, type val, int memorder);示例
int counter = 0;
int old = __atomic_fetch_add(&counter, 1, __ATOMIC_SEQ_CST);常见内存序
__ATOMIC_RELAXED__ATOMIC_ACQUIRE__ATOMIC_RELEASE__ATOMIC_ACQ_REL__ATOMIC_SEQ_CST
说明
现代 C++ 项目中,更推荐优先考虑 std::atomic,因为:
- 可读性更好
- 跨平台更规范
- 更符合现代 C++ 设计
但在底层库、运行时、编译器相关代码中,__atomic 仍很常见。
9. 栈与返回地址相关
9.1 __builtin_return_address
作用
获取当前函数调用者的返回地址。
示例
void* p = __builtin_return_address(0);应用
- 调试
- 简单调用链分析
- 崩溃定位辅助
注意
- 可移植性较差
- 在优化开启后结果未必稳定
- 不适合作为通用业务逻辑手段
9.2 __builtin_frame_address
作用
获取当前栈帧地址。
void* p = __builtin_frame_address(0);主要用于调试或底层运行时分析。
10. 实战场景总结
10.1 算法竞赛 / 位运算题
最常用:
__builtin_popcount__builtin_ctz__builtin_clz__builtin_ffs
示例:枚举集合中的所有元素下标
void printBits(unsigned int x) {
while (x) {
int i = __builtin_ctz(x);
cout << i << " ";
x &= (x - 1);
}
}10.2 高性能服务
常用:
__builtin_expect__builtin_prefetch__builtin_unreachable
示例:热路径优化
#define LIKELY(x) __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)
int process(int x) {
if (UNLIKELY(x < 0)) {
return -1;
}
return x * 2;
}10.3 底层并发编程
常用:
__sync_xxx__atomic_xxx
但如果不是在写底层库,优先考虑:
#include <atomic>
std::atomic<int> counter{0};
counter.fetch_add(1, std::memory_order_relaxed);11. 常见坑点
11.1 对 0 使用 clz/ctz
以下行为未定义:
__builtin_ctz(0);
__builtin_clz(0);使用前先判断:
if (x) {
cout << __builtin_ctz(x) << endl;
}11.2 搞错整数宽度
例如:
long long x;
__builtin_popcount(x); // 不严谨更合适:
__builtin_popcountll(x);应根据类型选择:
int-> 基本版long->llong long->ll
11.3 过度依赖编译器扩展
如果项目要求高可移植性,建议:
- 优先用标准库
- 对性能关键路径再局部使用
__builtin - 用宏或封装统一兼容不同编译器
12. 推荐封装写法
为了可读性更好,可以做一层简单封装:
namespace bitutil {
inline int popcount(unsigned int x) {
return __builtin_popcount(x);
}
inline int popcount(unsigned long long x) {
return __builtin_popcountll(x);
}
inline int trailing_zero_count(unsigned int x) {
return x ? __builtin_ctz(x) : 32;
}
inline int leading_zero_count(unsigned int x) {
return x ? __builtin_clz(x) : 32;
}
inline int highest_bit(unsigned int x) {
return x ? 31 - __builtin_clz(x) : -1;
}
}使用时更清晰:
cout << bitutil::popcount(15u) << endl;
cout << bitutil::highest_bit(18u) << endl;13. 与现代 C++ 标准库的对应关系
C++20 起,标准库已经提供了不少位操作工具,很多场景可以替代部分 __builtin:
#include <bit>对应关系大致如下:
__builtin_popcount->std::popcount__builtin_ctz->std::countr_zero__builtin_clz->std::countl_zero- 最高位相关 ->
std::bit_width - 2 的幂判断 ->
std::has_single_bit
示例:
#include <bit>
#include <iostream>
using namespace std;
int main() {
unsigned int x = 40;
cout << std::popcount(x) << endl;
cout << std::countr_zero(x) << endl;
cout << std::countl_zero(x) << endl;
}结论
如果你使用的是现代 C++(尤其 C++20 及以上):
- 业务代码优先标准库
- 性能极限场景或编译器绑定场景再使用
__builtin
14. 一份速查表
| 函数 | 作用 | 注意点 |
|---|---|---|
__builtin_popcount(x) | 统计 1 的个数 | 注意类型宽度 |
__builtin_parity(x) | 判断 1 的个数奇偶 | 返回 0/1 |
__builtin_ctz(x) | 统计末尾 0 个数 | x=0 未定义 |
__builtin_clz(x) | 统计前导 0 个数 | x=0 未定义 |
__builtin_ffs(x) | 返回第一个 1 的位置 | 位置从 1 开始 |
__builtin_expect(x, v) | 分支预测提示 | 只是提示 |
__builtin_unreachable() | 标记不可达 | 到达则未定义 |
__builtin_prefetch(p) | 预取内存 | 需实测收益 |
__sync_fetch_and_add | 旧式原子加 | 老接口 |
__atomic_fetch_add | 新式原子加 | 推荐胜过 __sync |
15. 建议记住的高频结论
最值得优先掌握的是这几个:
__builtin_popcount(x):数二进制中有多少个1__builtin_ctz(x):找最低位1__builtin_clz(x):找最高位1__builtin_expect(x, v):分支预测提示__builtin_prefetch(p):缓存预取
如果你是:
- 算法方向:重点掌握
popcount / ctz / clz / ffs - 系统方向:再掌握
expect / unreachable / prefetch / atomic - 现代工程方向:同时了解它们和 C++20
<bit>的对应替代
16. 附:一个综合示例
#include <bit>
#include <iostream>
using namespace std;
#define LIKELY(x) __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)
int main() {
unsigned int x = 44; // 101100
cout << "popcount = " << __builtin_popcount(x) << '\n';
cout << "trailing zeros = " << __builtin_ctz(x) << '\n';
cout << "leading zeros = " << __builtin_clz(x) << '\n';
cout << "first set bit position = " << __builtin_ffs(x) << '\n';
if (LIKELY(x > 0)) {
cout << "highest bit index = " << 31 - __builtin_clz(x) << '\n';
}
cout << "std::popcount = " << std::popcount(x) << '\n';
return 0;
}17. 最后总结
__builtin 是 C++ 中非常实用的一组编译器扩展,尤其适合:
- 位运算优化
- 性能敏感路径
- 底层系统开发
- 并发原子操作
但使用原则应当是:
- 先保证正确性
- 再考虑性能
- 先选标准库
- 必要时再用编译器内建
本篇文章全部内容均由chatGPT生成