1

我有这个功能:

bool interpolate(const Mat &im, float ofsx, float ofsy, float a11, float a12, float a21, float a22, Mat &res)
{         
   bool ret = false;
   // input size (-1 for the safe bilinear interpolation)
   const int width = im.cols-1;
   const int height = im.rows-1;
   // output size
   const int halfWidth  = res.cols >> 1;
   const int halfHeight = res.rows >> 1;
   float *out = res.ptr<float>(0);
   const float *imptr  = im.ptr<float>(0);
   for (int j=-halfHeight; j<=halfHeight; ++j)
   {
      const float rx = ofsx + j * a12;
      const float ry = ofsy + j * a22;
      #pragma omp simd
      for(int i=-halfWidth; i<=halfWidth; ++i, out++)
      {
         float wx = rx + i * a11;
         float wy = ry + i * a21;
         const int x = (int) floor(wx);
         const int y = (int) floor(wy);
         if (x >= 0 && y >= 0 && x < width && y < height)
         {
            // compute weights
            wx -= x; wy -= y;
            int rowOffset = y*im.cols;
            int rowOffset1 = (y+1)*im.cols;
            // bilinear interpolation
            *out =
                (1.0f - wy) * ((1.0f - wx) * imptr[rowOffset+x]   + wx * imptr[rowOffset+x+1]) +
                (       wy) * ((1.0f - wx) * imptr[rowOffset1+x] + wx * imptr[rowOffset1+x+1]);
         } else {
            *out = 0;
            ret =  true; // touching boundary of the input            
         }
      }
   }
   return ret;
}

halfWidth非常随机:可以是9、84、20、95、111……我只是想优化一下这段代码,具体没看懂。

如您所见,内部for已经矢量化,但 Intel Advisor 建议这样做:

在此处输入图像描述

这是 Trip Count 分析结果:

在此处输入图像描述

据我了解,这意味着:

  1. 向量长度为​​8,也就是说每个循环可以同时处理8个浮点数。这意味着(如果我没记错的话)数据是 32 字节对齐的(尽管正如我在这里解释的那样,编译器似乎认为数据没有对齐)。
  2. 平均而言,2 个循环是完全矢量化的,而 3 个循环是余数循环。最小值和最大值也是如此。否则我不明白什么;意思。

现在我的问题是:我如何才能遵循英特尔顾问的第一个建议?它说“增加对象的大小并添加迭代,因此行程计数是矢量长度的倍数”......好吧,所以它只是说“嘿,伙计这样做halfWidth*2+1(因为它从-halfWidthto+halfWidth是一个倍数8)"。但是我该怎么做呢?如果我添加随机循环,这显然会破坏算法!

我想到的唯一解决方案是添加这样的“假”迭代:

const int vectorLength = 8;
const int iterations = halfWidth*2+1;
const int remainder = iterations%vectorLength;

for(int i=0; i<loop+length-remainder; i++){
  //this iteration was not supposed to exist, skip it!
  if(i>halfWidth) 
     continue;
}

当然,这段代码不会工作,因为它从-halfWidthto 开始halfWidth,但它是为了让你了解我的“假”迭代策略。

关于第二个选项(“增加静态和自动对象的大小,并使用编译器选项添加数据填充”)我不知道如何实现这一点。

4

1 回答 1

1

首先,您必须检查 Vector Advisor Efficiency 指标以及与 Loop Body 相比在 Loop Remainder 中花费的相对时间(请参阅 Advisor 中的热点列表)。如果效率接近 100%(或者在 Remainder 中花费的时间非常少),那么它不值得努力(以及评论中提到的 MSalters 的钱)。

如果它是 << 100%(并且该工具没有报告其他惩罚),那么您可以重构代码以“添加假迭代”(很少有用户可以负担得起),或者您应该尝试#pragma loop_count来处理最典型的#it​​erations 值(取决于典型的 halfWidth 值)。

如果 halfWIdth 是完全随机的(没有共同值或平均值),那么您对这个问题无能为力。

于 2020-05-21T10:44:25.173 回答