我有这个功能:
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 分析结果:
据我了解,这意味着:
- 向量长度为8,也就是说每个循环可以同时处理8个浮点数。这意味着(如果我没记错的话)数据是 32 字节对齐的(尽管正如我在这里解释的那样,编译器似乎认为数据没有对齐)。
- 平均而言,2 个循环是完全矢量化的,而 3 个循环是余数循环。最小值和最大值也是如此。否则我不明白什么
;
意思。
现在我的问题是:我如何才能遵循英特尔顾问的第一个建议?它说“增加对象的大小并添加迭代,因此行程计数是矢量长度的倍数”......好吧,所以它只是说“嘿,伙计这样做halfWidth*2
+1(因为它从-halfWidth
to+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;
}
当然,这段代码不会工作,因为它从-halfWidth
to 开始halfWidth
,但它是为了让你了解我的“假”迭代策略。
关于第二个选项(“增加静态和自动对象的大小,并使用编译器选项添加数据填充”)我不知道如何实现这一点。