【发布时间】:2012-06-22 01:28:08
【问题描述】:
我已经用boost::numeric::ublas::matrix 实现了一个矩阵乘法(参见my full, working boost code)
Result result = read ();
boost::numeric::ublas::matrix<int> C;
C = boost::numeric::ublas::prod(result.A, result.B);
另一种使用标准算法(见full standard code):
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 秒,而提升实施获得了超过 4 分钟!
edit: 用
编译后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 比我的实现慢这么多?
【问题讨论】:
-
重新发明轮子是一个好主意的唯一时间是你可以制造一个更好的轮子......
-
Boost.uBLAS 是一个标准的接口,而不是一个强大的实现,所以不要期望它很快,除非你是使用例如LAPACK 后端。
-
Boost uBLAS 有一些可选的调试检查会减慢速度。请参阅此常见问题解答boost.org/doc/libs/1_49_0/libs/numeric/ublas/doc/index.htm,并检查预处理器宏 BOOST_UBLAS_NDEBUG 和 NDEBUG
-
虽然读取几个 2k×2k 矩阵不需要 4 分钟。
-
@Mysticial 棘手的部分是,大多数重新发明轮子的人通常都相信不管它是否真的更好,否则他们可能一开始就不会这样做。 :-D
标签: c++ performance boost ublas boost-ublas