我已经使用boost::numeric::ublas::matrix实现了一个矩阵乘法(请参见我的完整、可工作的boost代码)
Result result = read ();
boost::numeric::ublas::matrix<int> C;
C = boost::numeric::ublas::prod(result.A, result.B);
还有一个使用标准算法的实现(参见完整的标准代码):
vector< vector<int> > ijkalgorithm(vector< vector<int> > A,
vector< vector<int> > B) {
int n = A.size();
// initialise C with 0s
vector<int> tmp(n, 0);
vector< vector<int> > C(n, tmp);
for (int i = 0; i < n; i++) {
for (int k = 0; k < n; k++) {
for (int j = 0; j < n; j++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
return C;
}
这是我测试速度的方法:
time boostImplementation.out > boostResult.txt
diff boostResult.txt correctResult.txt
time simpleImplementation.out > simpleResult.txt
diff simpleResult.txt correctResult.txt
这两个程序读取一个硬编码的文本文件,其中包含两个 2000 x 2000 的矩阵。 这两个程序都使用了相同的编译标志:
g++ -std=c++98 -Wall -O3 -g $(PROBLEM).cpp -o $(PROBLEM).out -pedantic
我的实现需要15秒,而使用boost库则需要超过4分钟!
编辑:在编译后进行了修改。
g++ -std=c++98 -Wall -pedantic -O3 -D NDEBUG -DBOOST_UBLAS_NDEBUG library-boost.cpp -o library-boost.out
我用ikj算法得到了28.19秒的结果,而使用Boost则需要60.99秒。因此,Boost仍然明显比我的实现慢。
为什么Boost比我的实现慢这么多?