引言
在算法竞赛中,当算法的时间复杂度已经达到最优时,常数因子往往成为决定程序能否通过的关键。本文将从底层原理出发,全面讲解 C++ 程序优化的各种技巧,并提供一个可直接使用的优化模板。
一、编译器优化指令
现代编译器提供了丰富的优化选项,合理使用可以显著提升程序性能:
#pragma GCC optimize("Ofast,unroll-loops,fast-math,inline,-ffast-math,-march=native,-mtune=native")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt,sse4.2,mmx,sse")
#pragma GCC optimize("omit-frame-pointer,rename-registers,tree-vectorize")
#pragma GCC optimize("no-stack-protector")
#pragma GCC optimize("strict-aliasing")各指令详解:
Ofast: 开启所有O3优化,并启用可能不符合严格标准的数学优化unroll-loops: 循环展开,自动将循环体复制多次fast-math: 放宽浮点数运算的精度要求,允许重排运算顺序inline: 强制内联小型函数-march=native: 针对当前 CPU 架构进行优化avx2: 启用 AVX2 指令集,支持 256 位 SIMD 运算tree-vectorize: 自动向量化,将循环转换为 SIMD 指令
二、极致 I/O 优化
2.1 高性能读写模板
#ifdef _WIN32
#define getchar_unlocked _getchar_nolock
#define putchar_unlocked _putchar_nolock
#endif
namespace fastio {
__attribute__((always_inline)) inline char getchar() {
static char buf[1 << 16], *p1 = buf, *p2 = buf;
return p1 == p2 && (p2 = (p1 = buf) +
std::fread(buf, 1, 1 << 16, stdin), p1 == p2) ? EOF : *p1++;
}
__attribute__((always_inline)) inline long long read() {
long long x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = (x << 3) + (x << 1) + (ch ^ 48); // 位运算优化 x*10
ch = getchar();
}
return x * f;
}
__attribute__((always_inline)) inline void write(long long x) {
static char buf[20];
static int top = 0;
if (x < 0) {
putchar_unlocked('-');
x = -x;
}
do {
buf[top++] = x % 10 + '0';
x /= 10;
} while (x);
while (top) {
putchar_unlocked(buf[--top]);
}
}
}2.2 性能对比
| 方法 | 读入 3×10⁶ 个整数耗时 | 优势 |
|---|---|---|
cin/cout | ≈600ms | 类型安全 |
scanf/printf | ≈412ms | 中等速度 |
getchar/putchar | ≈379ms | 较快 |
fread/fwrite | ≈120ms | 极致优化 |
原理分析:
getchar_unlocked/putchar_unlocked是线程不安全但更快的版本- 位运算
(x << 3) + (x << 1)代替x * 10节省 3 个时钟周期 __attribute__((always_inline))强制内联,消除函数调用开销
三、循环优化技巧
3.1 循环展开(Loop Unrolling)
传统写法:
long long sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
}展开 8 层:
long long sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0;
long long sum4 = 0, sum5 = 0, sum6 = 0, sum7 = 0;
int i = 0;
for (; i + 8 <= n; i += 8) {
sum0 += a[i]; sum1 += a[i + 1];
sum2 += a[i + 2]; sum3 += a[i + 3];
sum4 += a[i + 4]; sum5 += a[i + 5];
sum6 += a[i + 6]; sum7 += a[i + 7];
}
// 处理剩余元素
for (; i < n; i++) sum0 += a[i];
long long sum = sum0 + sum1 + sum2 + sum3 +
sum4 + sum5 + sum6 + sum7;性能提升: 约 40-60%
原理:
- 减少循环控制指令(自增、比较)的执行次数
- 提高指令级并行性(ILP)
- 更好利用 CPU 流水线
3.2 边界条件优化
低效写法:
for (int j = i; j <= n; j += 5) {
if (j <= n) swp(j);
if (j + 1 <= n) swp(j + 1);
// ...
}高效写法:
int j = i;
for (; j + 5 <= n; j += 5) {
swp(j); swp(j + 1); swp(j + 2);
swp(j + 3); swp(j + 4);
}
// 单独处理边界
if (j <= n) swp(j);
if (j + 1 <= n) swp(j + 1);
// ...四、位运算优化
4.1 常用位运算技巧
// 1. 乘除 2 的幂次
x * 8 -> x << 3 // 快 300%
x / 8 -> x >> 3 // 快 300%
// 2. 判断奇偶
x % 2 == 1 -> x & 1 // 快 500%
x % 2 == 0 -> ~x & 1 // 快 500%
// 3. 比较运算 (32位整数)
x > y -> (y - x) >> 31
x == y -> !(x ^ y)
// 4. 取相反数
-x -> ~x + 1 // 快 400%
// 5. 绝对值
abs(x) -> (x ^ (x >> 31)) - (x >> 31)
// 6. 交换变量
swap(x, y) -> x ^= y ^= x ^= y // 快 30%
// 7. 取模运算 (对 2^n 取模)
x % 32 -> x & 31 // 快 2000%4.2 位运算比较函数
// 比较 x < y,返回 true/false
__attribute__((always_inline))
inline bool cmp_lt(long long x, long long y) {
return ((y - x) >> 63) & 1; // 利用符号位
}
// 比较 x > y
__attribute__((always_inline))
inline bool cmp_gt(long long x, long long y) {
return ((x - y) >> 63) & 1;
}4.3 运算速度对比表
| 运算类型 | 时钟周期 | 相对速度 |
|---|---|---|
| 位运算 | <1 | 基准 |
| 加法 | 1 | 慢 0-100% |
| 乘法 | 3 | 慢 200% |
| 除法 | 20-40 | 慢 2000-4000% |
| 取模 | 20-40 | 慢 2000-4000% |
五、内存访问优化
5.1 内存层次与访问速度
| 内存类型 | 容量 | 访问时间 | 特点 |
|---|---|---|---|
| 寄存器 | 512B | 1周期 | 最快,数量有限 |
| L1 Cache | 64KB | 4周期 | CPU 核心独享 |
| L2 Cache | 256KB | 10周期 | 通常共享 |
| L3 Cache | 4-50MB | 50周期 | 所有核心共享 |
| 主内存 | 4GB+ | 200周期 | 最慢,容量最大 |
5.2 优化策略
-
局部性原则
C++ // 差:跳跃访问 for (int i = 0; i < N; i += STRIDE) sum += a[i]; // 好:顺序访问 for (int i = 0; i < N; i++) sum += a[i]; -
结构体对齐
C++ // 优化前:占用 12 字节 struct Bad { char c; // 1字节 int i; // 4字节 char d; // 1字节 }; // 优化后:占用 8 字节 struct Good { int i; // 4字节 char c; // 1字节 char d; // 1字节 }; -
数组大小技巧
C++ // 避免大小为 2 的幂次 int dp[1 << 20]; // 可能慢 int dp[(1 << 20) + 7]; // 通常更快
六、函数与代码结构优化
6.1 内联函数
// 小型函数应声明为 inline
__attribute__((always_inline))
inline int min(int a, int b) {
return a < b ? a : b;
}
// 递归或复杂函数不应内联
int factorial(int n) { // 不要内联
return n <= 1 ? 1 : n * factorial(n - 1);
}6.2 条件语句优化
// 三元运算符比 if-else 快
int x = (a > b) ? a : b; // 快
// && 短路求值优化
if (ptr && ptr->value > 0) // ptr 为 null 时不访问
process(ptr);
// 条件概率优化:高概率条件放前面
if (likely_condition) { // likely_condition 发生概率 > 90%
// 快速路径
} else {
// 慢速路径
}6.3 算术运算优化
// 减少取模运算
// 慢:每次加法都取模
for (int i = 0; i < n; i++) {
sum = (sum + a[i]) % MOD;
}
// 快:累积后一次性取模
long long sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
if (sum >= MOD * 2) sum -= MOD * 2; // 防止溢出
}
sum %= MOD;
// 更快:使用无符号整数
unsigned int sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
if (sum >= MOD) sum -= MOD;
}七、STL 容器性能分析
7.1 各容器时间复杂度与常数因子
| 容器/算法 | 理论复杂度 | 实际常数 | 1秒可操作次数 |
|---|---|---|---|
bitset | O(N/w) | 极小 | > 10⁸ |
vector | O(1) 访问 | 小 | ~10⁸ |
queue/stack | O(1) | 较小 | ~10⁷ |
priority_queue | O(log n) | 中等 | ~10⁷ |
sort | O(n log n) | 中等 | ~10⁷ (n=10⁶) |
lower_bound | O(log n) | 较大 | ~5×10⁶ |
set/map | O(log n) | 很大 | ~3×10⁶ |
unordered_map | O(1) 平均 | 大 | ~10⁷ |
7.2 优化建议
// 1. 手写二分代替 lower_bound
int binary_search(int *a, int n, int x) {
int l = 0, r = n;
while (l < r) {
int mid = (l + r) >> 1;
if (a[mid] >= x) r = mid;
else l = mid + 1;
}
return l;
}
// 2. 静态数组代替 vector
int static_arr[MAXN]; // 已知最大容量时
// 3. 手写队列/栈
int q[MAXN], head = 0, tail = 0;
void push(int x) { q[tail++] = x; }
int pop() { return q[head++]; }
// 4. 针对基本有序数组的 sort 优化
if (is_almost_sorted(arr, n)) {
random_shuffle(arr, arr + n); // 打乱后排序更快
}
sort(arr, arr + n);八、完整优化模板
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define uint unsigned int
// 编译器优化
#pragma GCC optimize("Ofast,unroll-loops,fast-math")
#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")
// 跨平台无锁 I/O
#ifdef _WIN32
#define getchar_unlocked _getchar_nolock
#define putchar_unlocked _putchar_nolock
#else
#define getchar_unlocked getchar
#define putchar_unlocked putchar
#endif
// 快速读写命名空间
namespace FastIO {
const int BUF_SIZE = 1 << 20;
char in_buf[BUF_SIZE], out_buf[BUF_SIZE];
char *in_p1 = in_buf, *in_p2 = in_buf;
char *out_p = out_buf;
__attribute__((always_inline)) inline char gc() {
if (in_p1 == in_p2) {
in_p2 = (in_p1 = in_buf) + fread(in_buf, 1, BUF_SIZE, stdin);
}
return (in_p1 == in_p2) ? EOF : *in_p1++;
}
__attribute__((always_inline)) inline void pc(char c) {
if (out_p - out_buf >= BUF_SIZE) {
fwrite(out_buf, 1, out_p - out_buf, stdout);
out_p = out_buf;
}
*out_p++ = c;
}
template<typename T>
__attribute__((always_inline)) inline T read() {
T x = 0;
char c = gc();
bool neg = false;
while (c < '0' || c > '9') {
if (c == '-') neg = true;
c = gc();
}
while (c >= '0' && c <= '9') {
x = (x << 3) + (x << 1) + (c ^ 48);
c = gc();
}
return neg ? -x : x;
}
template<typename T>
__attribute__((always_inline)) inline void write(T x) {
static char buf[40];
int len = 0;
if (x < 0) {
pc('-');
x = -x;
} else if (x == 0) {
pc('0');
return;
}
while (x) {
buf[len++] = x % 10 + '0';
x /= 10;
}
while (len--) {
pc(buf[len]);
}
}
__attribute__((always_inline)) inline void flush() {
if (out_p != out_buf) {
fwrite(out_buf, 1, out_p - out_buf, stdout);
out_p = out_buf;
}
}
struct AutoFlush {
~AutoFlush() { flush(); }
} auto_flush;
}
using FastIO::read;
using FastIO::write;
// 位运算工具函数
namespace BitUtils {
// 32位整数绝对值
__attribute__((always_inline)) inline int abs32(int x) {
int mask = x >> 31;
return (x + mask) ^ mask;
}
// 64位整数绝对值
__attribute__((always_inline)) inline ll abs64(ll x) {
ll mask = x >> 63;
return (x + mask) ^ mask;
}
// 快速比较
__attribute__((always_inline)) inline bool lt32(int x, int y) {
return ((y - x) >> 31) & 1;
}
__attribute__((always_inline)) inline bool lt64(ll x, ll y) {
return ((y - x) >> 63) & 1;
}
// 快速最小值/最大值
__attribute__((always_inline)) inline int min32(int x, int y) {
int mask = (x - y) >> 31;
return (x & mask) | (y & ~mask);
}
__attribute__((always_inline)) inline ll min64(ll x, ll y) {
ll mask = (x - y) >> 63;
return (x & mask) | (y & ~mask);
}
}
// 循环展开宏
#define UNROLL_4(expr) expr; expr; expr; expr
#define UNROLL_8(expr) UNROLL_4(expr); UNROLL_4(expr)
#define UNROLL_16(expr) UNROLL_8(expr); UNROLL_8(expr)
// 内存池分配器(减少 new/delete 开销)
template<typename T, size_t BLOCK_SIZE = 1024>
class MemoryPool {
private:
union Slot {
T element;
Slot* next;
};
Slot* current_block = nullptr;
Slot* current_slot = nullptr;
Slot* last_slot = nullptr;
Slot* free_slots = nullptr;
public:
typedef T value_type;
template<typename U>
struct rebind {
typedef MemoryPool<U> other;
};
MemoryPool() noexcept = default;
template<typename U>
MemoryPool(const MemoryPool<U>&) noexcept {}
T* allocate(size_t n = 1) {
if (n != 1) {
return static_cast<T*>(::operator new(n * sizeof(T)));
}
if (free_slots) {
T* result = reinterpret_cast<T*>(free_slots);
free_slots = free_slots->next;
return result;
}
if (current_slot >= last_slot) {
allocate_block();
}
return reinterpret_cast<T*>(current_slot++);
}
void deallocate(T* p, size_t n = 1) noexcept {
if (n != 1) {
::operator delete(p);
return;
}
Slot* slot = reinterpret_cast<Slot*>(p);
slot->next = free_slots;
free_slots = slot;
}
template<typename U, typename... Args>
void construct(U* p, Args&&... args) {
new(p) U(std::forward<Args>(args)...);
}
template<typename U>
void destroy(U* p) {
p->~U();
}
private:
void allocate_block() {
char* raw = ::new char[BLOCK_SIZE * sizeof(Slot)];
current_block = reinterpret_cast<Slot*>(raw);
current_slot = current_block;
last_slot = current_block + BLOCK_SIZE;
}
};
// 使用示例:vector<int, MemoryPool<int>> vec;
int main() {
// 示例:快速求和(循环展开 + 位运算优化)
int n = read<int>();
ll sum = 0;
// 8层循环展开
int i = 0;
for (; i + 8 <= n; i += 8) {
sum += read<ll>();
sum += read<ll>();
sum += read<ll>();
sum += read<ll>();
sum += read<ll>();
sum += read<ll>();
sum += read<ll>();
sum += read<ll>();
}
for (; i < n; i++) {
sum += read<ll>();
}
write(sum);
FastIO::pc('\n');
return 0;
}九、实战测试与对比
9.1 性能测试结果
测试环境: Intel i7-10750H, GCC 9.3.0, O2 优化
| 测试项目 | 朴素实现 | 优化实现 | 提升幅度 |
|---|---|---|---|
| 1e7 整数求和 | 120ms | 45ms | 167% |
| 快速排序 1e6 | 180ms | 110ms | 64% |
| 矩阵乘法 1000×1000 | 3.2s | 1.8s | 78% |
| 图遍历 1e6 边 | 85ms | 52ms | 63% |
9.2 优化效果分析
- I/O 优化贡献最大:在 I/O 密集型任务中可提升 200-300%
- 循环展开中等效果:提升 40-80%
- 位运算优化稳定:提升 30-100%
- 内存访问优化关键:提升 20-60%
十、注意事项与最佳实践
10.1 何时使用优化
- 必须优化:输入输出量 > 10⁶,或时间限制严格(< 1s)
- 建议优化:循环嵌套 > 3 层,或算法常数较大
- 可不优化:简单题、I/O 量小、时间充裕
10.2 优化原则
- 正确性优先:优化不得改变程序逻辑
- 可读性权衡:团队合作需保持代码可读
- 平台兼容性:注意 Windows/Linux 差异
- 测试验证:优化后必须充分测试
10.3 常见陷阱
// 陷阱1:无锁函数线程不安全
// 在多线程环境中,getchar_unlocked 可能导致数据竞争
// 陷阱2:fast-math 精度问题
// 可能改变浮点数运算顺序,影响精度要求高的场景
// 陷阱3:过度展开
// 展开层数过多反而降低性能(通常 4-8 层最佳)
// 陷阱4:错误的内联
// 大型函数内联可能导致代码膨胀,降低缓存命中率