出于好奇,我决定对比一下自己的矩阵乘法函数和BLAS实现...结果让我大吃一惊:
Custom Implementation, 10 trials of 1000x1000 matrix multiplication:
Took: 15.76542 seconds.
BLAS Implementation, 10 trials of 1000x1000 matrix multiplication:
Took: 1.32432 seconds.
这是使用单精度浮点数。
我的实现:
template<class ValT>
void mmult(const ValT* A, int ADim1, int ADim2, const ValT* B, int BDim1, int BDim2, ValT* C)
{
if ( ADim2!=BDim1 )
throw std::runtime_error("Error sizes off");
memset((void*)C,0,sizeof(ValT)*ADim1*BDim2);
int cc2,cc1,cr1;
for ( cc2=0 ; cc2<BDim2 ; ++cc2 )
for ( cc1=0 ; cc1<ADim2 ; ++cc1 )
for ( cr1=0 ; cr1<ADim1 ; ++cr1 )
C[cc2*ADim2+cr1] += A[cc1*ADim1+cr1]*B[cc2*BDim1+cc1];
}
我有两个问题:
- 考虑到矩阵乘法,例如:nxm * mxn 需要 n*n*m 次乘法,在上述情况下需要 1000^3 或 1e9 次操作。在我的 2.6Ghz 处理器上,为什么 BLAS 可以在 1.32 秒内执行 10*1e9 次操作?即使乘法是单个操作且没有其他操作,也应该需要 ~4 秒。
- 为什么我的实现速度如此之慢?