在 Linux 下用 C++ 提升效率,通常可以从编译、算法、系统调用、并发、内存、工具几个层面入手。下面按实战优先级给你一个较系统的总结。
-O2 # 常用
-O3 # 更激进(有时反而变慢)
-Ofast # 忽略严格标准(科学计算可用)
-march=native
示例:
g++ -O2 -march=native main.cpp
-flto # Link Time Optimization
-fno-rtti # 不需要 RTTI 时
-fno-exceptions # 不抛异常时
| 场景 | 推荐 |
|---|---|
| 随机访问 | vector |
| 频繁插入删除 | list / deque |
| 查找 | unordered_map |
| 有序 | map |
❌ 避免 vector 中间插入
✅ 用 reserve() 预分配
void f(const std::string& s); // ✅
void f(std::string s); // ❌
std::vector<int> g() {
std::vector<int> v(1000);
return v; // 自动 move
}
vector > listnew/delete → 自定义 allocatorjemalloc / tcmallocLD_PRELOAD=/usr/lib/libtcmalloc.so ./app
readv/writevmmap 大文件io_uring(Linux 5.1+,极快)epoll(网络)// io_uring 示例略(可单独讲)
sendfilesplicestd::thread
std::async
std::atomic#include <sched.h>
cpu_set_t cpuset;
CPU_SET(0, &cpuset);
sched_setaffinity(0, sizeof(cpuset), &cpuset);
❌ 在循环中:
cout << endl(用 \n)new✅ 用:
std::arrayconstexprinlinetime ./app
top / htop
perf top
perf record ./app
perf report
valgrind --tool=callgrind
gprofFlameGraph❌ 慢
for (int i = 0; i < v.size(); i++)
sum += v[i];
✅ 快
int s = 0;
for (int x : v) s += x;
✅ 更快
#include <numeric>
sum = std::accumulate(v.begin(), v.end(), 0);
如果你愿意,可以告诉我:
我可以给你针对性优化方案或代码示例。