在 CentOS 上优化 C++ 程序性能,通常可以从编译器优化、系统配置、代码层面、运行环境、性能分析工具等多个维度入手。下面给你一个比较系统、实战向的优化指南。
yum install devtoolset-11
scl enable devtoolset-11 bash
-O2 # 常用,性价比最高
-O3 # 激进优化,可能增大体积
-Ofast # 忽略严格标准(慎用)
-march=native # 针对当前 CPU 优化
-flto # 链接时优化
示例:
g++ -O3 -march=native -flto main.cpp -o app
std::vector 频繁扩容std::vector<T> v;
v.reserve(1000);
std::unordered_map vs std::mapstd::string_view(C++17)new/deletestd::thread / std::asyncalignas(64) int counter;
#include <pthread.h>
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(0, &cpuset);
pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset);
适合大内存、高性能程序(如数据库、缓存)
echo 1024 > /proc/sys/vm/nr_hugepages
systemctl disable firewalld
systemctl disable tuned
ulimit -n 1000000
cpupower frequency-set -g performance
perf stat ./app
perf record ./app
perf report
g++ -pg main.cpp -o app
./app
gprof app gmon.out
valgrind --tool=cachegrind ./app
g++ -static main.cpp -o app
jemalloctcmallocyum install jemalloc
g++ main.cpp -ljemalloc
mmap 替代 read/writeio_uring, libaio)❌ 盲目 -O3
❌ 过度优化不热路径
❌ 过早优化
❌ 忽略 profiling 数据
你可以直接贴代码或说明使用场景(例如:网络服务、计算密集型、实时系统等)。