在 Linux 下进行 C++ 性能优化,通常可以从编译、系统、算法、内存、并发、工具几个层面入手。下面给出一个比较系统、可落地的优化思路。
-O2 # 常用
-O3 # 更激进(注意稳定性)
-Ofast # 牺牲严格标准(浮点)
-march=native # 针对本机 CPU
-flto # 链接期优化
示例:
g++ -O3 -march=native -flto main.cpp
-DNDEBUG
-g 在性能敏感场景const、constexpr| 场景 | 推荐 |
|---|---|
| 随机访问 | vector |
| 频繁插入删除 | list / deque |
| 查找 | unordered_map |
| 有序数据 | flat_map |
❌ 避免:
vector 中间频繁插入map 做高频查找alignas(64) struct Data { ... };
new/deletestd::vector::reservemovestd::string_viewstd::movestd::threadstd::asyncatomicspinlock(短临界区)#define _GNU_SOURCE
#include <sched.h>
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(0, &mask);
sched_setaffinity(0, sizeof(mask), &mask);
top
htop
vmstat 1
iostat -x 1
perf stat ./app
ulimit -n 100000
perf 做热点分析perf record ./app
perf report
valgrind --tool=callgrind ./app
perf script | ./stackcollapse-perf.pl | ./flamegraph.pl > out.svg
❌ 过度使用虚函数
❌ 在循环里 new
❌ 滥用 shared_ptr
❌ 无意义的 try-catch
❌ 频繁系统调用(如 cout)
for (int i = 0; i < v.size(); i++) {
sum += v[i];
}
int sum = 0;
for (const int x : v) sum += x;
或更激进:
#include <numeric>
sum = std::accumulate(v.begin(), v.end(), 0);
先测量,再优化;先算法,再系统;先缓存,再并发。
如果你愿意,可以告诉我:
我可以直接给你针对性优化方案。