SSE3内在函数:如何找到大量浮点数的最大值

ved*_*eda 7 c++ sse intrinsics

我有以下代码来查找最大值

int length = 2000;
float *data;
// data is allocated and initialized

float max = 0.0;
for(int i = 0; i < length; i++)
{
   if(data[i] > max)
   {
      max = data;
   }
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用SSE3内在函数进行矢量化,但我对如何进行比较感到震惊.

int length = 2000;
float *data;
// data is allocated and initialized

float max = 0.0;
// for time being just assume that length is always mod 4
for(int i = 0; i < length; i+=4)
{
  __m128 a = _mm_loadu_ps(data[i]);
  __m128 b = _mm_load1_ps(max);

  __m128 gt = _mm_cmpgt_ps(a,b);

  // Kinda of struck on what to do next
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以提出一些想法.

Joh*_*nck 10

因此,您的代码在固定长度的浮点数组中找到最大值.好.

有_mm_max_ps,它从两个向量的四个浮点数给出成对最大值.那怎么样?

int length = 2000;
float *data; // maybe you should just use the SSE type here to avoid copying later
// data is allocated and initialized

// for time being just assume that length is always mod 4
__m128 max = _mm_loadu_ps(data); // load the first 4
for(int i = 4; i < length; i+=4)
{
  __m128 cur = _mm_loadu_ps(data + i);
  max = _mm_max_ps(max, cur);
}
Run Code Online (Sandbox Code Playgroud)

最后,抓取四个值中的最大值max(请参阅使用SSE获取__m128i向量中的最大值?).

它应该这样工作:

步骤1:

[43, 29, 58, 94] (this is max)
[82, 83, 10, 88]
[19, 39, 85, 77]
Run Code Online (Sandbox Code Playgroud)

第2步:

[82, 83, 58, 94] (this is max)
[19, 39, 85, 77]
Run Code Online (Sandbox Code Playgroud)

第2步:

[82, 83, 85, 94] (this is max)
Run Code Online (Sandbox Code Playgroud)