Linux 下 C++ 的“配置优化”通常可以从 编译构建、运行时、系统环境、代码设计 四个层面来做。下面按常见场景给你一个比较系统的优化清单,你可以对号入座。
-O2 # 推荐,性价比最高
-O3 # 激进优化(可能增大体积,不一定更快)
-Os # 优化体积
-Ofast # 忽略严格标准(浮点、math),慎用
-O2 -march=native -mtune=native
-march=native:使用当前 CPU 的全部指令集(AVX / AVX2 / AVX512)-mtune=native:针对当前 CPU 做调度优化⚠️ 注意:
-march=native 不能跨机器运行
-flto
示例:
g++ -O2 -flto main.cpp foo.cpp -o app
✅ 对大型项目效果明显
❌ 编译时间变长
-s # 去掉符号表
-DNDEBUG # 关闭 assert
-g -Og
set(CMAKE_BUILD_TYPE Release)
set(CMAKE_CXX_FLAGS_RELEASE "-O2 -march=native -flto")
或者现代写法:
target_compile_options(app PRIVATE
$<$<CONFIG:Release>:-O2 -march=native -flto>
)
make -j$(nproc)
或 CMake:
cmake --build . --parallel $(nproc)
-static-libgcc -static-libstdc++
x86_64-linux-musl-g++
-ljemalloc
适合:
#define _GNU_SOURCE
#include <sched.h>
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(0, &cpuset);
sched_setaffinity(0, sizeof(cpuset), &cpuset);
systemctl disable bluetooth
systemctl disable cups
ulimit -n 100000
ulimit -s 8192
sysctl -w net.core.somaxconn=65535
sysctl -w vm.swappiness=10
std::vector<bool>reserve()std::string 拼接void foo(const std::string& s); // ✅
void foo(std::string s); // ❌
unordered_map vs mapflat_map(absl / boost)-Wall -Wextra -Wpedantic
perf stat ./app
perf record ./app
perf report
valgrind --tool=memcheck ./app
heaptrack ./app
-O2 -g -Wall -Wextra
-O2 -march=native -flto -DNDEBUG
我可以给更具体的优化方案,比如:
我可以直接给你一套 可复制的 CMake + 编译参数 + 系统配置模板。