在 CentOS 上通过 GCC 优化程序性能,通常可以从编译选项、系统环境、代码层面、工具链几个方面入手。下面按实用程度给你一个较完整的指南。
-O2 # 推荐,安全且高效(服务器程序常用)
-O3 # 更激进,可能增大体积,有时反而变慢
-Os # 优化体积(嵌入式/容器友好)
示例:
gcc -O2 main.c -o main
CentOS 常用于服务器,指定 CPU 可显著提升性能。
-march=native # 使用当前机器 CPU 指令集
-mtune=native # 针对当前 CPU 调优
示例:
gcc -O2 -march=native -mtune=native main.c -o main
查看 CPU 支持的指令集:
lscpu
cat /proc/cpuinfo | grep flags
常见:
x86-64avx2avx512(慎用,发热大)适合中大型项目。
gcc -O2 -flto -c a.c
gcc -O2 -flto -c b.c
gcc -O2 -flto a.o b.o -o app
或一步:
gcc -O2 -flto main.c -o main
-ftree-vectorize # 通常 -O3 默认开启
配合:
-ffast-math # 浮点加速(不保证 IEEE 严格)
示例:
gcc -O3 -march=native -ffast-math main.c
gcc -O2 -fopenmp main.c -o main
代码中:
#pragma omp parallel for
CentOS 7 默认 GCC 4.8,太老。
yum install centos-release-scl
yum install devtoolset-11
scl enable devtoolset-11 bash
gcc --version
支持版本:
cpupower frequency-set -g performance
查看:
cpupower frequency-info
tuned-adm profile throughput-performance
restrictvoid f(int *restrict a, int *restrict b);
static inline void foo() {}
或:
-finline-functions
printfyum install perf
perf record ./main
perf report
gcc -O2 -fopt-info -march=native main.c
gcc -O2 -fprofile-generate main.c
./main # 跑典型负载
gcc -O2 -fprofile-use main.c
gcc -O2 -march=native -mtune=native -flto main.c -o main
gcc -O3 -march=native -ffast-math -flto main.c -o main
gcc -O2 -march=x86-64 main.c
如果你能告诉我:
我可以给你定制一套最优编译参数。