c++ - 循环优化
问题描述
我有一个循环,里面有一个内循环。我该如何优化它以优化执行时间,例如避免多次访问同一事物的内存并尽可能避免加法和乘法。
int n,m,x1,y1,x2,y2,cnst;
int N = 9600;
int M = 1800;
int temp11,temp12,temp13,temp14;
int temp21,temp22,temp23,temp24;
int *arr1 = new int [32000]; // suppose it's already filled
int *arr2 = new int [32000];// suppose it's already filled
int sumFirst = 0;
int maxFirst = 0;
int indexFirst = 0;
int sumSecond = 0;
int maxSecond = 0;
int indexSecond = 0;
int jump = 2400;
for( n = 0; n < N; n++)
{
temp14 = 0;
temp24 = 0;
for( m = 0; m < M; m++)
{
x1 = m + cnst;
y1 = m + n + cnst;
temp11 = arr1[x1];
temp12 = arr2[y1];
temp13 = temp11 * temp12;
temp14+= temp13;
x2 = m + cnst + jump;
y2 = m + n + cnst + jump;
temp21 = arr1[x2];
temp22 = arr2[y2];
temp23 = temp21 * temp22;
temp24+= temp23;
}
sumFirst += temp14;
if (temp14 > maxFirst)
{
maxFirst = temp14;
indexFirst = m;
}
sumSecond += temp24;
if (temp24 > maxSecond)
{
maxSecond = temp24;
indexSecond = n;
}
}
// At the end we use sum , index and max for first and second;
解决方案
您正在将数组元素相乘并累积结果。这可以通过以下方式进行优化:
- SIMD(在单个 CPU 步骤中执行多项操作)
- 并行执行(一次使用多个物理/逻辑 CPU)
寻找特定于 CPU 的 SIMD 方式来执行此操作。像_mm_mul_epi32
SSE4.1 一样,可能可以在 x86-64 上使用。在尝试使用编译器内在函数编写您自己的 SIMD 版本之前,请确保编译器尚未为您执行此操作。
至于并行执行,看 omp,或者使用 C++17 并行累积。
推荐阅读
- tensorflow - 神经网络不训练
- sql - 将数据库中所有表的前 100 行数据透视到列中
- android - 在 Kotlin 中无法识别 Android 可为空的注释
- python - Python 在传感器的 DLL 中调用 SDK 函数,该函数获取指针 IP 和端口并返回 void*(void* 配置文件传感器的句柄。)
- phpstorm - 如何让 PhpStorm 在调试控制台中更改字体?
- docker - Windows 上的 Docker 和 WSL Ubuntu 找不到 docker-entrypoint.sh - 找不到文件
- python - 为 django 测试创建经过身份验证的用户
- c++ - boost::asio 将动态大小的数据传递给异步处理程序的问题
- activiti - 暂停流程实例
- android - 为什么我恢复的项目在 Firebase 控制台中不可见?