在 Ubuntu 下用 C++ 做性能优化,通常可以从编译选项、系统配置、代码层面、工具分析四个方向入手。下面按实用程度给你一个较完整的清单。
使用 g++ / clang++ 时:
g++ -O2 -march=native -mtune=native main.cpp -o app
常见选项:
-O2:常用优化(推荐)-O3:更激进(有时反而变慢,需测试)-march=native:针对当前 CPU 指令集优化-flto:链接期优化(大项目明显)-DNDEBUG:关闭 assert示例:
g++ -O2 -flto -march=native main.cpp -o app
Ubuntu 默认是 ld,可换:
sudo apt install lld
g++ -fuse-ld=lld main.cpp -o app
sudo apt install g++-12
g++-12 -std=c++20 ...
systemctl disable bluetooth
sudo apt install cpufrequtils
sudo cpufreq-set -g performance
jemalloc / tcmalloc 替代 glibc mallocsudo apt install libjemalloc-dev
g++ main.cpp -ljemalloc
new/deletestd::vector::reservestd::vector<int> v;
v.reserve(100000);
void f(const std::string& s); // ✅
void f(std::string s); // ❌
使用 std::move:
std::vector<int> a;
std::vector<int> b = std::move(a);
#include <thread>
或使用:
std::asyncg++ -fopenmp main.cpp -o app
std::atomicshared_mutexsudo apt install linux-tools-common
perf record ./app
perf report
查看:
g++ -pg main.cpp -o app
./app
gprof app gmon.out
sudo apt install valgrind
valgrind --tool=callgrind ./app
perf script | FlameGraph/stackcollapse-perf.pl | FlameGraph/flamegraph.pl > out.svg
❌ 频繁 cout
✅ 用 printf 或缓冲输出
❌ 在循环里 string + string
✅ std::ostringstream 或 reserve
❌ 滥用虚函数 ✅ 模板 / CRTP
perf 找热点如果你愿意,可以:
我可以直接帮你做针对性优化建议。