假设我以以下方式定义一个简单的身份:
SparseMatrix<double> spIdent(N,N);
spIdent.reserve(N);
spIdent.setIdentity();
然后对其执行这些操作
spIdent-spIdent;
spIdent*spIdent;
spIdent - spIdent*spIdent;
并测量所有三个的计算时间。我得到的结果是这样的
0 Computation time: 2.6e-05
1 Computation time: 2e-06
2 Computation time: 1.10706
意思是任何一种操作都很快,但组合起来就变得非常慢。
noalias()
方法仅适用于密集矩阵,在我提供的密集示例中并没有太大的区别。有什么启示吗?MCVE:
#include <iostream>
#include <ctime>
#include "../Eigen/Sparse"
using namespace std;
using namespace Eigen;
int main() {
unsigned int N=2000000;
SparseMatrix<double> spIdent(N,N);
spIdent.reserve(N);
spIdent.setIdentity();
clock_t start=clock();
spIdent*spIdent;
cout << "0 Computation time: " << float(clock() - start)/1e6 << '\n';
start=clock();
spIdent-spIdent;
cout << "1 Computation time: " << float(clock() - start)/1e6 << '\n';
start=clock();
spIdent - (spIdent*spIdent);
cout << "2 Computation time: " << float(clock() - start)/1e6 << '\n';
return 0;
}