使用 SSE 缩放复杂向量

Scaling of a complex vector using SSE

我想将 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;
}

您可能想要这样的东西:

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 中看到任何好处。