在 Linux(或更准确地说,在 GCC/Clang
编译器)中,提供了一些内置函数(Built-in
Functions),用于高效执行底层操作(如位运算、原子操作、CPU
指令优化等)。这些函数通常直接映射到特定的 CPU 指令,性能极高。
1. 位操作相关内置函数
(1) 计算
1
的个数(Population Count)
int __builtin_popcount(unsigned int x); int __builtin_popcountll(unsigned long long x);
|
示例:
#include <iostream> int main() { int num = 0b1101; std::cout << __builtin_popcount(num); return 0; }
|
底层指令:POPCNT
(现代 CPU 支持)
(2) 计算前导零(Leading
Zeros)
int __builtin_clz(unsigned int x); int __builtin_clzll(unsigned long long x);
|
示例:
int num = 0b00010000; std::cout << __builtin_clz(num);
|
注意:
- 如果
x = 0
,结果是未定义的(UB)。
- 在 32 位系统中,
__builtin_clz(1)
返回
31
(因为 1
的二进制是
000...0001
)。
(3) 计算末尾零(Trailing
Zeros)
int __builtin_ctz(unsigned int x); int __builtin_ctzll(unsigned long long x);
|
示例:
int num = 0b1000; std::cout << __builtin_ctz(num);
|
注意:
(4) 位反转(Bit
Reversal)
unsigned int __builtin_bitreverse32(unsigned int x); unsigned long long __builtin_bitreverse64(unsigned long long x);
|
示例:
int num = 0b1101; std::cout << __builtin_bitreverse32(num);
|
2. 原子操作(Atomic
Operations)
用于无锁编程(Lock-Free Programming),避免数据竞争。
(1) 原子加法
int __atomic_add_fetch(int* ptr, int val, int memorder);
|
示例:
int x = 5; __atomic_add_fetch(&x, 3, __ATOMIC_SEQ_CST); std::cout << x;
|
(2) 原子比较交换(CAS)
bool __atomic_compare_exchange(int* ptr, int* expected, int desired, bool weak, int success_memorder, int failure_memorder);
|
示例:
int x = 10; int expected = 10; bool success = __atomic_compare_exchange(&x, &expected, 20, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); if (success) std::cout << "CAS succeeded!";
|
3. 内存屏障(Memory
Barrier)
用于控制 CPU 和编译器的内存访问顺序。
__atomic_thread_fence(int memorder); __atomic_signal_fence(int memorder);
|
常用内存序(Memory Order):
__ATOMIC_RELAXED
(最弱约束)
__ATOMIC_SEQ_CST
(最强约束,默认)
4. 数学优化
(1)
快速平方根倒数(近似计算)
float __builtin_sqrtf(float x); double __builtin_sqrt(double x);
|
(2) 快速乘加运算(FMA)
float __builtin_fmaf(float a, float b, float c); double __builtin_fma(double a, double b, double c);
|
5. 其他实用内置函数
(1) 预测分支(Branch
Prediction)
if (__builtin_expect(condition, expected_value)) { ... }
|
示例:
if (__builtin_expect(x > 0, 1)) { }
|
(2) 返回当前函数地址
void* __builtin_return_address(unsigned int level);
|
示例:
void* caller_address = __builtin_return_address(0);
|
总结
功能 |
内置函数 |
说明 |
计算 1 的个数 |
__builtin_popcount |
高效统计二进制 1 的数量 |
计算前导零 |
__builtin_clz |
计算高位连续零的个数 |
计算末尾零 |
__builtin_ctz |
计算低位连续零的个数 |
原子操作 |
__atomic_add_fetch |
无锁编程(线程安全) |
内存屏障 |
__atomic_thread_fence |
控制内存访问顺序 |
分支预测优化 |
__builtin_expect |
提升条件分支性能 |
这些内置函数在 Linux
内核、高性能计算、编译器优化
中广泛使用,能显著提升代码效率。