版本比较
浅谈:C++卡常小技巧,如何让同样的代码更快? V4
标题
增加 1 行删除 1 行
11浅谈:C++卡常小技巧,如何让同样的代码更快? V3浅谈:C++卡常小技巧,如何让同样的代码更快? V4正文
增加 184 行删除 378 行
1234567869101112135 行未改动192021222023242526272829303132303334353637383940353637384142434041424344454647484950515253545556575859606162636465666768697071727374754445464748495051525354555657585960616263646566676869707971728182838485867374888990917576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913020 行未改动1511521531541211551561571581591601611621631301641651661678 行未改动1761771781791471801811821831844 行未改动18919019119216016116216319319416516616719519616917017119719819920020120220320420520617317420720820921021121221321421517617721621721821922022122222322417918022522622722822923023123218218318423323423523623723823924024124218624324424524624724824925018818919019119219325125225325425525625725825919519619719826026126226326426526626726826927027127227327427527627727827928028128228328428528628728820 行未改动3093103113122293133142313153162333173183193203213 行未改动32532632732824532933033133233335 行未改动36937037137228937337437537637723 行未改动40140240340432140540640740840921 行未改动431432433434351435436437438439440357358359360361362441442365443444367368369370371445446373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614447448449450451452453454455624456457458459460461462631463464465633634635636637638639640641642643644645646647648649650651652653654655656657658659660466[看运气进的博客](https://blog.pyas.top/post/6)
本文部分借助Deepseek完成,并已审核,如果有问题,请私信我修正,谢谢!
V4版本后文章已经重新编写了部分内容!
## 引言
在算法竞赛中,当算法的时间复杂度已经达到最优时,常数因子往往成为决定程序能否通过的关键。本文将从底层原理出发,全面讲解 C++ 程序优化的各种技巧,并提供一个可直接使用的优化模板。在算法竞赛中,当算法的时间复杂度已经达到最优时,常数因子往往成为决定程序能否通过的关键。本文将从底层原理出发,全面讲解 C++ 程序优化的各种技巧。
## 一、编译器优化指令
现代编译器提供了丰富的优化选项,合理使用可以显著提升程序性能:5 行未改动#pragma GCC optimize("no-stack-protector")#pragma GCC optimize("strict-aliasing")```
**各指令详解:****各指令详解(Deepseek的解释):**
1. **`Ofast`**: 开启所有 `O3` 优化,并启用可能不符合严格标准的数学优化2. **`unroll-loops`**: 循环展开,自动将循环体复制多次3. **`fast-math`**: 放宽浮点数运算的精度要求,允许重排运算顺序4. **`inline`**: 强制内联小型函数5. **`-march=native`**: 针对当前 CPU 架构进行优化6. **`avx2`**: 启用 AVX2 指令集,支持 256 位 SIMD 运算7. **`tree-vectorize`**: 自动向量化,将循环转换为 SIMD 指令
## 二、极致 I/O 优化## 二、I/O 优化(输入输出优化)
### 2.1 高性能读写模板
据说还有一种名为`mmap`的快读方法,不过作者不会,[参考这篇站内文章](https://www.luogu.com.cn/article/2pbig65w)写得很优秀
这里介绍一种使用`fread`读入,`fwrite`输出的方法,模板如下:```cpp#ifdef _WIN32#define getchar_unlocked _getchar_nolock#define putchar_unlocked _putchar_nolock#endif#include <cstdio>#include <cstdlib>
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]); } }static char in_buf[1<<20], *p1=in_buf, *p2=in_buf;inline char gc() { return p1==p2&&(p2=(p1=in_buf)+fread(in_buf,1,1<<20,stdin),p1==p2)?EOF:*p1++; }inline int read() { int x=0,f=1; char c=gc(); while(c<'0'||c>'9') {if(c=='-')f=-1;c=gc();} while(c>='0'&&c<='9') x=x*10+c-'0',c=gc(); return x*f;}
static char out_buf[1<<20], *op=out_buf;inline void pc(char c) { if(op==out_buf+1<<20)fwrite(out_buf,1,1<<20,stdout),op=out_buf; *op++=c; }inline void write(int x) { if(x<0) pc('-'),x=-x; char stk[10]; int top=0; do stk[top++]=x%10+'0',x/=10; while(x); while(top) pc(stk[--top]);}inline void flush() { fwrite(out_buf,1,op-out_buf,stdout); }__attribute__((constructor)) void reg() { atexit(flush); }
int main() { int a=read(), b=read(); write(a), pc(' '), write(b), pc('\n'); return 0;}```
### 2.2 性能对比当然也有一种效率比`fread`低的快读快写,优点是代码少,好背:
| 方法 | 读入 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))` 强制内联,消除函数调用开销```cppinline void read(unsigned long long &a) {a = 0;char c;while ((c = getchar()) < 48);do a = a * 10 + (c ^ 48);while ((c = getchar()) > 47);}//这种方法适用于不大于2^64的正整数。```
```cppinline void read(int& a) { int s = 0, w = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') w = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { s = s * 10 + ch - '0'; ch = getchar(); } a = s * w;//这种比上面慢,比scanf快5倍。}```
**快写**:
```cppvoid write(int x) { static int sta[35]; int top = 0; do { sta[top++] = x % 10; x /= 10; } while (x); while (top) putchar(sta[--top] + '0');}//使用栈来实现,比普通的快写更快```
### 2.2 性能对比
| 方法 | 读入 3×10⁶ 个整数耗时 | 优势 | 难度 ||------|----------------------|------|------|| `cin/cout` | ≈600ms | 类型安全 | 非常好写 || `scanf/printf` | ≈412ms | 中等速度 | 好写 || `getchar/putchar` | ≈379ms | 较快 | 两个小函数 || `fread/fwrite` | ≈120ms | **快** | 需要花时间记忆 |
## 三、循环优化技巧
### 3.1 循环展开(Loop Unrolling)
20 行未改动
// 处理剩余元素for (; i < n; i++) sum0 += a[i];
long long sum = sum0 + sum1 + sum2 + sum3 + long long sum = sum0 + sum1 + sum2 + sum3 + sum4 + sum5 + sum6 + sum7;```
**性能提升:** 约 40-60%
**原理:**- 减少循环控制指令(自增、比较)的执行次数- 提高指令级并行性(ILP)- 更好利用 CPU 流水线
### 3.2 边界条件优化
**低效写法:**8 行未改动**高效写法:**```cppint j = i;for (; j + 5 <= n; j += 5) { swp(j); swp(j + 1); swp(j + 2); swp(j); swp(j + 1); swp(j + 2); swp(j + 3); swp(j + 4);}// 单独处理边界if (j <= n) swp(j);4 行未改动## 四、位运算优化
### 4.1 常用位运算技巧
```cpp// 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%至于条件是什么,我们来看看Deepseek怎么说:
// 3. 比较运算 (32位整数)x > y -> (y - x) >> 31x == y -> !(x ^ y)```cpp// 1. 乘 2 的幂次(以8为例)// 原写法:x * 8// 优化写法:x << 3// 限制条件:// 1) x 为整数类型(int/long long 等);// 2) 移位位数不超过对应类型的位数(如32位int不超过31位);// 3) 乘法无溢出(溢出行为在C++中未定义)。int mul_pow2 = x << 3; // 等价于 x * 8(满足限制条件时)
// 4. 取相反数-x -> ~x + 1 // 快 400%// 2. 除 2 的幂次(以8为例)// 原写法:x / 8// 优化写法:x >> 3// 限制条件:// 1) x 为非负整数(负数右移是算术右移,如-9>>3=-2,但-9/8=-1,结果不符);// 2) 移位位数不超过对应类型的位数;// 3) 除数必须是 2 的正整数次幂。int div_pow2 = x >> 3; // 等价于 x / 8(仅非负整数有效)
// 5. 绝对值abs(x) -> (x ^ (x >> 31)) - (x >> 31)// 3. 判断整数奇偶性// 3.1 判断奇数// 原写法:x % 2 == 1// 优化写法:x & 1// 限制条件:// 1) x 为非负整数(负数如-3,x%2=-1≠1,但x&1=1,结果不符);// 2) 仅适用于二进制补码架构(主流CPU均满足)。bool is_odd = (x & 1); // 等价于 x % 2 == 1(仅非负整数有效)
// 6. 交换变量swap(x, y) -> x ^= y ^= x ^= y // 快 30%// 3.2 判断偶数// 原写法:x % 2 == 0// 优化写法:!(x & 1)(替代~x & 1,可读性更高)// 限制条件:// 1) x 为非负整数(负数如-2,x%2=0,但~x&1=1,结果不符);// 2) 推荐用!(x&1),避免~运算符的易错性。bool is_even = !(x & 1); // 等价于 x % 2 == 0(仅非负整数有效)
// 7. 取模运算 (对 2^n 取模)x % 32 -> x & 31 // 快 2000%```// 4. 32位整数比较运算// 4.1 判断 x > y// 原写法:x > y// 优化写法:(y - x) >> 31// 限制条件:// 1) x、y 为32位有符号整数;// 2) y - x 无溢出(如y=INT_MAX、x=INT_MIN时,y-x溢出,结果错误);// 3) 结果:0 表示x>y,-1 表示x≤y(需结合逻辑非判断)。bool is_greater = !((y - x) >> 31); // 等价于 x > y(无溢出时有效)
### 4.2 位运算比较函数// 4.2 判断 x == y// 原写法:x == y// 优化写法:!(x ^ y)// 限制条件:// 1) x、y 为同类型整数;// 2) 无溢出风险,全架构/编译器通用。bool is_equal = !(x ^ y); // 等价于 x == y(通用有效
```cpp// 比较 x < y,返回 true/false__attribute__((always_inline)) inline bool cmp_lt(long long x, long long y) { return ((y - x) >> 63) & 1; // 利用符号位}// 5 取整数绝对值// 原写法:abs(x)// 优化写法:(x ^ (x >> 31)) - (x >> 31)// 限制条件:// 1) x 为32位有符号整数;// 2) x 不能是INT_MIN(绝对值超出32位int范围,结果仍为INT_MIN);// 3) 依赖算术右移(主流编译器均支持)。int abs_x = (x ^ (x >> 31)) - (x >> 31); // 等价于 abs(x)(x≠INT_MIN时有效)
// 比较 x > y__attribute__((always_inline))inline bool cmp_gt(long long x, long long y) { return ((x - y) >> 63) & 1;// 6. 交换整数变量// 原写法:swap(x, y)// 优化写法:x ^= y ^= x ^= y// 限制条件:// 1) x、y 为同类型整数;// 2) x 和 y 不能是同一个变量(否则会置0);// 3) 仅适用于整数,不支持浮点/指针等类型。void swap_int(int &x, int &y) { if (&x != &y) { // 避免同一变量导致错误 x ^= y; y ^= x; x ^= y; }}
// 7. 对 2^n 取模(以32为例)// 原写法:x % 32// 优化写法:x & 31(31 = 2^5 - 1)// 限制条件:// 1) x 为非负整数(负数如-5,x%32=-5,但x&31=27,结果不符);// 2) 模数必须是 2 的正整数次幂(模数=2^n → 掩码=2^n-1);// 3) 掩码不超过对应类型的位数。int mod_pow2 = x & 31; // 等价于 x % 32(仅非负整数有效)``````
### 4.3 运算速度对比表
| 运算类型 | 时钟周期 | 相对速度 |20 行未改动
1. **局部性原则** ```cpp // 差:跳跃访问 for (int i = 0; i < N; i += STRIDE) for (int i = 0; i < N; i += STRIDE) sum += a[i];
// 好:顺序访问 for (int i = 0; i < N; i++) for (int i = 0; i < N; i++) sum += a[i]; ```
2. **结构体对齐**3 行未改动 char c; // 1字节 int i; // 4字节 char d; // 1字节 };
// 优化后:占用 8 字节 struct Good { int i; // 4字节 char c; // 1字节35 行未改动if (ptr && ptr->value > 0) // ptr 为 null 时不访问 process(ptr);
// 条件概率优化:高概率条件放前面if (likely_condition) { // likely_condition 发生概率 > 90%if (helloworld) { // helloworld 发生概率 > 90% // 快速路径} else { // 慢速路径}23 行未改动 if (sum >= MOD) sum -= MOD;}```
## 七、STL 容器性能分析## 七、STL 容器性能
### 7.1 各容器时间复杂度与常数因子
| 容器/算法 | 理论复杂度 | 实际常数 | 1秒可操作次数 |21 行未改动 return l;}
// 2. 静态数组代替 vectorint static_arr[MAXN]; // 已知最大容量时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);```
## 八、完整优化模板## 八、实战测试与对比
```cpp#include <bits/stdc++.h>#define ll long long#define ull unsigned long long#define uint unsigned int### 8.1 性能测试结果
// 编译器优化#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 优化效果分析### 8.2 优化效果分析
1. **I/O 优化贡献最大**:在 I/O 密集型任务中可提升 200-300%2. **循环展开中等效果**:提升 40-80%3. **位运算优化稳定**:提升 30-100%4. **内存访问优化关键**:提升 20-60%
## 十、注意事项与最佳实践## 九、注意!!!每个优化都有与之对应的条件,请务必测试代码看看是否符合输出预期!!!
### 10.1 何时使用优化
1. **必须优化**:输入输出量 > 10⁶,或时间限制严格(< 1s)2. **建议优化**:循环嵌套 > 3 层,或算法常数较大3. **可不优化**:简单题、I/O 量小、时间充裕
### 10.2 优化原则
1. **正确性优先**:优化不得改变程序逻辑2. **可读性权衡**:团队合作需保持代码可读3. **平台兼容性**:注意 Windows/Linux 差异4. **测试验证**:优化后必须充分测试
### 10.3 常见陷阱
```cpp// 陷阱1:无锁函数线程不安全// 在多线程环境中,getchar_unlocked 可能导致数据竞争
// 陷阱2:fast-math 精度问题// 可能改变浮点数运算顺序,影响精度要求高的场景
// 陷阱3:过度展开// 展开层数过多反而降低性能(通常 4-8 层最佳)
// 陷阱4:错误的内联// 大型函数内联可能导致代码膨胀,降低缓存命中率```本文全部内容作者已在C++23中编译测试!