【发布时间】:2017-05-04 09:11:24
【问题描述】:
我有这个功能:
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 字节对齐的(尽管我解释 here 似乎编译器认为数据没有对齐)。
- 平均而言,2 个循环是完全矢量化的,而 3 个循环是余数循环。最小值和最大值也是如此。否则我不明白
;是什么意思。
现在我的问题是:如何遵循英特尔顾问的第一个建议?它说“增加对象的大小并添加迭代,因此行程计数是向量长度的倍数”......好吧,所以它只是说“嘿,伙计这样做halfWidth*2+1(因为它来自@ 987654331@ 到 +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 到halfWidth,但它是为了让你了解我的“假”迭代策略。
关于第二个选项(“增加静态和自动对象的大小,并使用编译器选项添加数据填充”)我不知道如何实现。
【问题讨论】:
-
“这意味着(如果我没记错的话)数据是 32 字节对齐的” - 不,现在还有一个未对齐的加载操作。但是,您必须针对一个足够新的架构,它肯定不在 SSE2 中。
-
“我想到的唯一解决方案是添加这样的“假”迭代:
if(i>halfWidth) continue;。您确实注意到了#pragma omp simd?就像在单指令多数据?因为你在那里提出了一个MIMD解决方案。对于SIMD,数据可以依赖[i],但指令不能。 -
@MSalters 对不起,我使用的是 AVX2 机器,这意味着寄存器是 256 位 = 32 字节 = 8 个浮点数。我错了吗?
-
@MSalters 我个人添加了
simd,但我不明白您的评论。我只是说:如果我们强制for迭代次数是 8 的倍数,则不会有余数循环,这会更有效,因为它完全适合寄存器。我错过了什么? -
您有一个带有 8 个浮点数的寄存器。你不能
continue循环半个寄存器。几乎每条 AVX2 指令都适用于整个 8 个浮点数。
标签: c++ parallel-processing vectorization simd intel-advisor