毕昇编译器循环优化实践
毕昇编译器循环优化实践
本文介绍如何使用毕昇编译器在 openEuler 系统上进行循环优化,通过实际案例展示性能提升的过程。
环境准备
实验需要以下环境:
- 系统:openEuler 22.03 LTS SP3
- 架构:AArch64
- 内存:8GB以上
服务器配置
以下是云服务器的推荐配置:
| 配置项 | 配置值 |
|---|---|
| 计费模式 | 按需计费 |
| 区域/可用区 | 华北-北京四 | 可用区1 |
| 实例规格 | 鲲鹏通用计算增强型 | kc1.xlarge.4 | 4vCPUs | 16GiB |
| 操作系统镜像 | openEuler-22.03-LTS-SP3 (aarch64)(V22.03) |
| 系统盘 | 通用型SSD, 50GiB |
连接服务器
使用SSH命令连接服务器:
ssh root@<服务器公网IP>
安装毕昇编译器
添加源
执行以下命令添加毕昇编译器的软件源:
dnf config-manager --add-repo https://repo.oepkgs.net/openeuler/rpm/openEuler-22.03-LTS/extras/aarch64/
更新源索引
运行以下命令更新软件包索引:
dnf update --nogpgcheck
安装编译器
安装BiShengCompiler:
dnf install BiShengCompiler.aarch64 --nogpgcheck
AutoTuner 工具安装
首先确保Python版本为3.11以上。如果需要,可以自行编译安装Python3.11:
sudo dnf groupinstall "Development Tools" -y
sudo dnf install openssl-devel bzip2-devel libffi-devel xz-devel sqlite-devel -y
wget https://registry.npmmirror.com/-/binary/python/3.11.9/Python-3.11.9.tgz
tar -xf Python-3.11.9.tgz
cd Python-3.11.9
./configure --enable-optimizations
make -j $(nproc)
sudo make altinstall
创建并激活虚拟环境:
python3.11 -m venv ~/autotuner_env
source ~/autotuner_env/bin/activate
实验一:循环展开
测试代码
编写一个包含密集计算的循环程序:
#include <stdio.h>
#define N 10000000
int main() {
int sum = 0;
for (int i = 0; i < N; i++) {
sum += i % 10;
}
printf("%d\n", sum);
return 0;
}
编译与优化
使用AutoTuner工具进行调优:
clang -O2 -o test_unroll test.c -fautotune-generate
export AUTOTUNE_DATADIR=~/autotune_data/
llvm-autotune minimize
for i in $(seq 10); do
clang -O2 -o test_autotuned test.c -fautotune
time_cost=$(./test_autotuned)
llvm-autotune feedback $time_cost
done
llvm-autotune finalize
clang -O2 -o test_final test.c -fautotune
实验二:循环合并
编写两个独立的循环,并使用AutoTuner工具进行优化,步骤与实验一类似。
实验三:强度削弱
编写一个包含乘法运算的循环程序,并观察编译器是否将其替换为加法运算。
实验四:循环分块
编写矩阵乘法程序,并观察不同优化等级下的性能差异。