首页 > 解决方案 > 循环优化

问题描述

我有一个循环,里面有一个内循环。我该如何优化它以优化执行时间,例如避免多次访问同一事物的内存并尽可能避免加法和乘法。

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;

标签: c++loopsoptimization

解决方案


您正在将数组元素相乘并累积结果。这可以通过以下方式进行优化:

  • SIMD(在单个 CPU 步骤中执行多项操作)
  • 并行执行(一次使用多个物理/逻辑 CPU)

寻找特定于 CPU 的 SIMD 方式来执行此操作。像_mm_mul_epi32SSE4.1 一样,可能可以在 x86-64 上使用。在尝试使用编译器内在函数编写您自己的 SIMD 版本之前,请确保编译器尚未为您执行此操作。

至于并行执行,看 omp,或者使用 C++17 并行累积。


推荐阅读