cpl*_*les 5 c++ parallel-processing intel vectorization intel-advisor
我正在尝试优化这个功能:
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;
}
Run Code Online (Sandbox Code Playgroud)
我正在使用英特尔顾问对其进行优化,即使内部for
已经矢量化,英特尔顾问仍检测到低效的内存访问模式:
特别是以下三个指令中有4个聚集(不规则)访问:
根据我的理解,当访问的元素属于类型 时,会发生收集访问的问题a[b]
,其中类型b
是不可预测的。这似乎就是 的情况imptr[rowOffset+x]
,其中 和rowOffset
都是x
不可预测的。
同时,我看到Vertical Invariant
当使用恒定偏移量访问元素时应该发生这种情况(再次,根据我的理解)。但实际上我不知道这个恒定的偏移量在哪里
所以我有3个问题:
使用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
Run Code Online (Sandbox Code Playgroud)
矢量化(SIMD 化)您的代码不会自动使您的访问模式变得更好(或更差)。为了最大限度地提高矢量化代码的性能,您必须尝试在代码中使用单位步长(也称为连续、线性、步长 1)内存访问模式。或者至少是“可预测的”常规步幅-N,其中 N 理想地应该是适度低的值。
如果不引入这种规律性,您可以在指令级别保持内存加载/存储操作部分顺序(非并行)。因此,每次您想要进行“并行”加法/乘法等时,您都必须进行“非并行”原始数据元素“收集”。
在您的情况下,似乎有常规的 stride-N (逻辑上) - 这可以从代码片段和 Advisor MAP 输出(在右侧面板上)中看到。 垂直不变性- 意味着您有时会在迭代之间访问相同的内存位置。单位步幅意味着在其他情况下您具有逻辑上连续的内存访问。
然而,代码结构很复杂:循环体内有 if 语句,有复杂的条件和浮点 --> 整数(简单但仍然)转换。
因此,编译器必须使用最通用和最低效的方法(收集)“以防万一”,因此您的物理、实际内存访问模式(来自编译器代码生成)是不规则的“GATHER”,但逻辑上您的访问模式是规则的(不变或单位步长)。
解决方案可能不是很容易,但我会尝试以下操作: