【发布时间】:2017-05-01 09:11:13
【问题描述】:
我正在尝试优化这个功能:
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个收集(不规则)访问:
据我了解,当访问的元素是a[b] 类型时,会发生收集访问的问题,其中b 是不可预测的。 imptr[rowOffset+x] 似乎就是这种情况,rowOffset 和 x 都是不可预测的。
同时,我看到Vertical Invariant 应该在以恒定偏移量访问元素时发生(根据我的理解)。但实际上我没有看到这个常量偏移量在哪里
所以我有 3 个问题:
- 我是否正确理解了收集访问的问题?
- Vertical Invariant 访问怎么样?我不太确定这一点。
- 最后,我该如何改进/解决这里的内存访问?
使用 icpc 2017 更新 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
【问题讨论】:
-
我唯一可以推荐的是确保您的 im Matrix 是 32 或 64 字节对齐的,以确保您没有额外的缓存未命中 - 确保 imptr[rowOffset+x] 是总是在同一个缓存行上,不管 x(在矩阵的范围内)
-
@xaxxon 感谢您的建议。如您所见,我是 simd 的新手,所以我有几个关于该主题的问题:32/64 字节对齐取决于架构,对吗?那么它是否改变了 AVX2 和 AVX-512 架构?我使用 AVX2 进行调试和矢量化评估,而使用 AVX-512(KNL 机器)进行性能评估。
-
啊,是的,臭名昭著的“按回车在评论中开始新行”评论:) 你不能只按回车,你必须执行以下步骤:
-
@xaxxon 我笑死了
-
您要确保您的数据结构不跨越缓存行。这取决于架构,是的,但 64 字节似乎是现代 CPU 上相当常见的大小。任何时候您进行这种级别的调整,它总是取决于系统。 software.intel.com/en-us/articles/…
标签: c++ parallel-processing vectorization intel intel-advisor