Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 479
veda Avatar asked Mar 06 '13 04:03

veda


1 Answers

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)
like image 178
John Zwinck Avatar answered Sep 20 '22 14:09

John Zwinck