内积运算是向量投影、测度计算中的常见运算,本节给出内积运算的SIMD加速版本,需要引用头文件“#include <xmmintrin.h>”。
int InnerProduct(float*x, float* y, const int&k, float& inner_prod)
{
__m128 X, Y; // 128-bit values
__m128 acc = _mm_setzero_ps(); // set to (0, 0, 0, 0)
float temp[4];
long i;
for (i = 0; i < k - 4; i += 4)
{
X = _mm_loadu_ps(x + i); // load chunk of 4 floats
Y = _mm_loadu_ps(y + i);
acc = _mm_add_ps(acc, _mm_mul_ps(X, Y));
}
_mm_storeu_ps(&temp[0], acc); // store acc into an array of floats
inner_prod = temp[0] + temp[1] + temp[2] + temp[3];
// add the remaining values
for (; i < k; i++)
inner_prod += x[i] * y[i];
return 1;
}