在 Debian 上优化 GCC 编译性能(既指“编译速度”,也指“生成程序的运行性能”)通常从以下几个方面入手。下面按使用场景分类说明。
apt install -t bullseye-backports gcc g++
apt install clang
ccache避免重复编译:
apt install ccache
export CC="ccache gcc"
export CXX="ccache g++"
make -j$(nproc)
CMake:
cmake --build . -j$(nproc)
对大型 C++ 项目有效:
// stdafx.h
#include <vector>
#include <string>
g++ -x c++-header stdafx.h -o stdafx.h.gch
include-what-you-use-O2 # 推荐默认
-O3 # 更高性能(可能更大)
-Os # 体积优先
示例:
g++ -O2 main.cpp
-march=native # 当前 CPU
-mtune=native
示例:
g++ -O2 -march=native main.cpp
非常有效
g++ -O2 -flto -c a.cpp
g++ -O2 -flto -c b.cpp
g++ -O2 -flto a.o b.o -o app
CMake:
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
-std=c++17 / c++20
新标准常带来更好优化。
g++ -O2 -fprofile-generate main.cpp
./a.out # 运行典型负载
g++ -O2 -fprofile-use main.cpp
-O3 -ftree-vectorize
查看:
fopts
gold / lld 链接器apt install binutils-gold
或:
-fuse-ld=lld
g++ -O2 -fopt-info
apt install linux-perf
perf stat ./app
服务器程序:
-O2 -march=native -flto
极致性能:
-O3 -march=native -flto -fprofile-use
快速编译:
-O1 -pipe -j$(nproc) + ccache
如果你能说明:
我可以给你更具体的优化方案。