在 Ubuntu 上用 C++ 提高性能,通常可以从编译优化、系统调优、代码层面、工具分析四个方向入手。下面给你一个比较系统、实用、可落地的总结。
使用 g++ / clang++ 时:
g++ -O2 -o app main.cpp
常用选项:
-O2:推荐,性价比高-O3:更高优化(可能增大体积、不稳定)-Ofast:忽略严格标准(如浮点),性能更高-march=native:针对当前 CPU 优化-flto:链接时优化(LTO)示例:
g++ -O3 -march=native -flto -o app main.cpp
Ubuntu 自带 gcc 可能较旧:
gcc --version
可安装新版:
sudo apt install g++-12
g++-12 -O3 main.cpp
或用 Clang(常更快):
sudo apt install clang
clang++ -O3 main.cpp
sudo apt install linux-tools-common
sudo cpupower frequency-set -g performance
查看:
lscpu
mmap 替代频繁 read/writestd::ios::sync_with_stdio(false))new/delete✅ 好:
std::vector<int> v;
v.reserve(1000000);
❌ 差:
std::vector<int> v;
for (...) v.push_back(x);
| 场景 | 推荐 |
|---|---|
| 随机访问 | vector |
| 频繁插入删除 | list / deque |
| 查找 | unordered_map |
| 有序 | map |
void f(const std::string& s); // ✅
void f(std::string s); // ❌
使用 std::move:
std::vector<int> v2 = std::move(v1);
#pragma omp parallel for
for (int i = 0; i < n; i++) {
...
}
编译:
g++ -fopenmp main.cpp
std::thread / std::async-O3)__attribute__((vector))Eigen(矩阵运算)sudo perf record ./app
sudo perf report
看:
g++ -pg main.cpp
./app
gprof app gmon.out
或:
valgrind --tool=callgrind ./app
❌ 频繁 cout
❌ 频繁 new/delete
❌ 大量 std::endl
❌ 递归过深
❌ 锁竞争
-O2 → 2x-O3 -march=native → +20%你可以直接贴代码或说明用途(比如:图像处理 / 服务端 / 算法竞赛)。