在 Linux 下用 C++ 做性能优化,通常可以从编译配置、系统配置、代码层面、运行环境四个维度入手。下面给你一套比较系统、实用的“升性能”方案。
-O2 # 常用,性价比高
-O3 # 更激进,个别场景反而变慢
-Ofast # 忽略严格标准(如浮点),性能更高
推荐:
g++ -O2 -march=native -flto
-march=native # 使用本机 CPU 指令集
-mtune=native
-flto
配合:
-Wl,-O2
sudo cpupower frequency-set -g performance
echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
#include <pthread.h>
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(0, &cpuset);
pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset);
或使用 taskset:
taskset -c 0,1,2,3 ./app
std::vector::reservenew/delete 频繁调用void f(const std::string& s); // ✅
void f(std::string s); // ❌
使用:
std::moveemplace_backstd::threadstd::atomicalignas(64) int a;
perf top
perf record ./app
perf report
valgrind --tool=massif
heaptrack
perf script | FlameGraph/stackcollapse-perf.pl | FlameGraph/flamegraph.pl > out.svg
cout / printfstd::mapg++ -O3 -march=native -flto -pthread -std=c++20 main.cpp -o app
如果你愿意,可以告诉我:
我可以直接给你针对性的优化方案或代码示例。