SSE3 intrinsics: How to find the maximum of a large array of floats

不羁岁月 提交于 2019-12-08 19:08:56

问题


I have the following code to find the maximum value

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;
   }
}

I tried vectorizing it by using SSE3 intrinsics, but I am kind of struck on how I should do the comparison.

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
}

Can anyone give some idea on it.


回答1:


So your code finds the largest value in a fixed-length array of floats. OK.

There is _mm_max_ps, which gives you the pairwise maxima from two vectors of four floats each. So how about this?

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);
}

Finally, grab the largest of the four values in max (see Getting max value in a __m128i vector with SSE? for that).

It should work this way:

Step 1:

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

Step 2:

[82, 83, 58, 94] (this is max)
[19, 39, 85, 77]

Step 2:

[82, 83, 85, 94] (this is max)


来源:https://stackoverflow.com/questions/15238978/sse3-intrinsics-how-to-find-the-maximum-of-a-large-array-of-floats

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!