选项 -fauto-profile,-fporfile-correction
说明
与插桩式反馈优化不同,自动反馈优化使用perf收集程序的运行信息,然后使用create_gcov工具解析来自perf的采样信息为编译器所需profile,最后使用选项-fauto-profile读取profile完成优化。
选项-fprofile-correction用于使能mcf算法,平滑由于采样导致的基本块计数不均衡。
使用方法
测试用例 test.c 如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #define ARRAY_LEN 30000 static struct timeval tm1; static inline void start() { gettimeofday(&tm1, NULL); } static inline void stop() { struct timeval tm2; gettimeofday(&tm2, NULL); unsigned long long t = 1000 * (tm2.tv_sec - tm1.tv_sec) +\ (tm2.tv_usec - tm1.tv_usec) / 1000; printf("%llu ms\n", t); } void bubble_sort (int *a, int n) { int i, t, s = 1; while (s) { s = 0; for (i = 1; i < n; i++) { if (a[i] < a[i - 1]) { t = a[i]; a[i] = a[i - 1]; a[i - 1] = t; s = 1; } } } } void sort_array() { printf("Bubble sorting array of %d elements\n", ARRAY_LEN); int data[ARRAY_LEN], i; for(i=0; i<ARRAY_LEN; ++i) { data[i] = rand(); } bubble_sort(data, ARRAY_LEN); } int main() { start(); sort_array(); stop(); return 0; } |
- 安装软件包
自动反馈优化需要使用perf工具采样程序热点信息,使用create_gcov工具生成编译器所需profile。在openEuler 22.03 LTS及以上版本,可以使用如下命令安装:
1
yum install perf autofdo
- 编译时增加调试信息
自动反馈优化要求程序中包含调试信息,因此需要使用-g选项增加调试信息,以test程序为例:
1
gcc -g -O2 -o test test.c
- 生成profile
自动反馈优化使用perf收集profile。
- 对于Arm架构,使用如下命令完成perf文件的采集和profile的生成:
1 2
perf record -e inst_retired:u -- ./test create_gcov --binary=./test --profile=perf.data --gcov=test.gcov -gcov_version=1 --use_lbr=0
- 对于x86_64架构,使用如下命令完成perf文件的采集和profile的生成:
1 2
perf record -b -e br_inst_retired.near_taken:pp -- ./test create_gcov --binary=./test --profile=perf.data --gcov=test.gcov -gcov_version=1
- 对于Arm架构,使用如下命令完成perf文件的采集和profile的生成:
- 启用优化
增加编译器选项-fauto-profile使能自动反馈优化:
1
gcc -g -O2 -o test test.c -fauto-profile=test.gcov
增加编译器选项-fprofile-correction使能mcf算法(可选):
1
gcc -g -O2 -o test test.c -fauto-profile=test.gcov -fprofile-correction
注:mcf算法效果与实际应用场景有关,建议充分测试后使用。
父主题: 静态编译优化