参考http://blogs.msdn.com/b/xiangfan/archive/2009/04/28/optimize-your-code-matrix-multiplication.aspx。
template<>
void SeqMatrixMult4(int size, float** m1, float** m2, float** result)
{
Transpose(size, m2);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
__m128 c = _mm_setzero_ps();
for (int k = 0; k < size; k += 4) {
c = _mm_add_ps(c, _mm_mul_ps(_mm_load_ps(&m1[i][k]), _mm_load_ps(&m2[j][k])));
}
c = _mm_hadd_ps(c, c);
c = _mm_hadd_ps(c, c);
_mm_store_ss(&result[i][j], c);
}
}
Transpose(size, m2);
}
为什么_mm_hadd_ps(c, c)
在最里面的 for 循环之后还有 2 个?为了验证我的理解:此代码从 m1 加载 4 个浮点数,从 m2 加载另外 4 个浮点数,然后将它们相乘得到 4 个浮点数 ( __m128
)。然后我将它们相加c
(此时,它仍然是 4 个浮点数?)。然后在for循环之后我hadd
这个结果两次?那有什么作用?
我稍微重写的代码会产生错误的结果
long long start, end;
__m128 v1, v2, vMul, vRes;
vRes = _mm_setzero_ps();
start = wall_clock_time();
transpose_matrix(m2);
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
float tmp = 0;
for (int k = 0; k < SIZE; k+=4) {
v1 = _mm_load_ps(&m1[i][k]);
v2 = _mm_load_ps(&m2[j][k]);
vMul = _mm_mul_ps(v1, v2);
vRes = _mm_add_ps(vRes, vMul);
}
vRes = _mm_hadd_ps(vRes, vRes);
_mm_store_ss(&result[i][j], vRes);
}
}
end = wall_clock_time();
fprintf(stderr, "Optimized Matrix multiplication took %1.2f seconds\n", ((float)(end - start))/1000000000);
// reverse the transposition
transpose_matrix(m2);