在 Linux 下使用 GCC 优化程序性能,通常可以从编译选项、代码层面、系统/链接、Profile 指导优化几个方面入手。下面按常用程度和收益从高到低介绍。
-O2
-O3
-Os
-march=native
-mtune=native
✅ 在本机运行效果最好
gcc -O2 -march=native -mtune=native main.c
指定目标机器(例如服务器):
-march=skylake -mtune=skylake
-ftree-vectorize # 自动向量化(O3 默认)
-funroll-loops # 循环展开
-finline-functions # 内联
-fomit-frame-pointer # 减少栈操作(调试会受影响)
示例:
gcc -O3 -march=native -funroll-loops -ffast-math main.c
⚠️ 会改变数学结果,不能用于金融/精度敏感场景
-ffast-math
允许:
gcc -O2 -flto -c a.c
gcc -O2 -flto -c b.c
gcc -O2 -flto a.o b.o -o app
✅ 可跨文件 inline、死代码消除
✅ 对大型项目效果明显
gcc -O2 -fprofile-generate -o app main.c
./app < input.txt
gcc -O2 -fprofile-use -o app main.c
✅ 对分支预测、热点函数效果极好
✅ 常用于数据库、编译器、浏览器
gcc -O2 -fopenmp main.c
-std=c11atomicinline
__attribute__((hot)) // 热点函数
__attribute__((cold)) // 冷路径
__builtin_expect()
示例:
if (__builtin_expect(err != 0, 0))
handle_error();
malloc/freeprintfgcc -O2 -fopt-info -c main.c
查看向量化:
gcc -O3 -fopt-info-vec -c main.c
gcc -O3 -march=native -mtune=native -flto -funroll-loops main.c -o app
gcc -O2 -march=x86-64 -mtune=generic -flto main.c -o app
❌ 不要盲目 -O3
❌ 不要 Debug + 高优化混用
❌ 不要忽略 -Wall -Wextra
❌ 不要忽略性能测试(benchmark)
如果你愿意,可以告诉我:
我可以给你一套针对性 GCC 优化参数。