使用SSE缩放复杂向量

时间:2016-05-04 15:53:39

标签: c x86 sse simd sse2

我想将SSE指令应用于包含复数的向量。没有SSE指令,我可以使用以下代码完成。但是,当我应用SSE指令时,我不知道如何将计算出的实部和虚部返回到数组中。我该如何解决这个问题?

complex double * complexScaling(complex double *input, double c, int length) 
{
  for(int i=0; i<length; i++) {
    input[i] = c*input[i];
  }
  return input;
}

complex double * complexScalingSSE(complex double *input, double c, int length) 
{
  __m128d multiplier,real,imag;
  multiplier = _mm_set1_pd(c);
  for(int i=0; i<length; i+=2) {
    real = _mm_set_pd(creal(input[i]),creal(input[i+1]));
    real = _mm_mul_pd(real, multiplier);
    imag = _mm_set_pd(cimag(input[i]),cimag(input[i+1]));
    imag = _mm_mul_pd(imag, multiplier);
  }
  return input;
}

1 个答案:

答案 0 :(得分:3)

你可能想要这样的东西:

complex double * complexScalingSSE(complex double *input, double c, int length)
{
    const __m128d vc = _mm_set1_pd(c);

    for (int i = 0; i < length; i++)
    {
        __m128d v = _mm_loadu_pd((double *)&input[i]);  // load one complex double
        v = _mm_mul_pd(v, vc);                          // scale it
        _mm_storeu_pd((double *)&input[i], v);          // store it
    }
    return input;
}

您可能希望尝试循环展开2倍(但请注意,对于大型向量,此例程可能会受I / O限制):

complex double * complexScalingSSE(complex double *input, double c, int length)
{
    const __m128d vc = _mm_set1_pd(c);
    int i;

    for (i = 0; i <= length - 2; i += 2)
    {
        __m128d v1 = _mm_loadu_pd((double *)&input[i]); // load two complex doubles
        __m128d v2 = _mm_loadu_pd((double *)&input[i + 1]);
        v1 = _mm_mul_pd(v1, vc);                        // scale them
        v2 = _mm_mul_pd(v2, vc);
        _mm_storeu_pd((double *)&input[i], v1);         // store them
        _mm_storeu_pd((double *)&input[i + 1], v2); 
    }
    if (i < length)                                     // handle odd element at end
    {
        __m128d v = _mm_loadu_pd((double *)&input[i]);  // load one complex double
        v = _mm_mul_pd(v, vc);                          // scale it
        _mm_storeu_pd((double *)&input[i], v);          // store it
    }
    return input;
}

另请注意,一个不错的编译器应该自动矢量化您的原始例程,在这种情况下,您不会看到手动编码SSE的任何好处。