我正在尝试优化这个函数:
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;
}
我正在使用Intel Advisor进行优化,即使内部的for
已经矢量化,Intel Advisor仍会检测到低效的内存访问模式:
- 60%的单位/零步幅访问
- 40%的不规则/随机步幅访问
特别地,在以下三条指令中有4个gather(不规则)访问:
据我理解,gather访问的问题在于所访问的元素是a[b]
类型的,其中b
是不可预测的。这似乎是imptr[rowOffset+x]
的情况,其中rowOffset
和x
都是不可预测的。
同时,我看到了这个Vertical Invariant
,这应该发生(再次阐述,从我的理解),当通过恒定偏移量访问元素时。但实际上,我不知道这个恒定偏移量在哪里。
所以我有3个问题:
- 我对gather访问的问题理解正确吗?
- 垂直不变访问呢?我对这一点不太确定。
- 最后,我该如何改进/解决这里的内存访问问题?
使用以下标志编译:icpc
2017 update 3。
INTEL_OPT=-O3 -ipo -simd -xCORE-AVX2 -parallel -qopenmp -fargument-noalias -ansi-alias -no-prec-div -fp-model fast=2 -fma -align -finline-functions
INTEL_PROFILE=-g -qopt-report=5 -Bdynamic -shared-intel -debug inline-debug-info -qopenmp-link dynamic -parallel-source-info=2 -ldl