我正在转换一些我自己的向量代数代码来使用优化的boost uBLAS库。然而,当我尝试做一个对称矩阵-SparseVector乘法时,我发现它比我自己的实现慢了大约4倍。向量大小通常在0-500左右,约70%-80%的条目为零。
这是我的密码
void CRoutines::GetA(double a[], double vectorIn[], int sparseVectorIndexes[], int vectorLength, int sparseLength)
{
compressed_vector<double> inVec (vectorLength, sparseLength);
for(int i = 0; i < sparseLength; i++)
{
inVec(sparseVectorIndexes[i]) = vectorIn[sparseVectorIndexes[i]];
}
vector<double> test = prod(inVec, matrix);
for(int i = 0; i < vectorLength; i++)
{
a[i] = test(i);
}
}sparseVectorIndexes存储输入向量的非零值的索引,vectorLength是向量的长度,sparseLength是向量中的非零数。该矩阵存储为对称矩阵symmetric_matrix<double, lower>。
我自己的实现是一个简单的嵌套循环迭代,其中矩阵只是一个2D双数组:
void CRoutines::GetA(double a[], double vectorIn[], int sparseVectorIndexes[], int vectorLength, int sparseLength)
{
for (int i = 0; i < vectorLength; i++)
{
double temp = 0;
for (int j = 0; j < sparseLength; j++)
{
int row = sparseVectorIndexes[j];
if (row <= i) // Handle lower triangular sparseness
temp += matrix[i][row] * vectorIn[row];
else
temp += matrix[row][i] * vectorIn[row];
}
a[i] = temp;
}}
为什么uBLAS的速度慢4x?我是不是没有把乘法写好?还是有另一个更适合这种情况的图书馆?
编辑:如果我使用密集向量数组,那么uBLAS只慢2倍.
发布于 2011-06-13 14:33:58
uBlas的设计并没有把性能作为第一目标。有些库比uBlas快得多。参见例如http://eigen.tuxfamily.org/index.php?title=Benchmark
发布于 2012-03-22 11:21:37
发布于 2011-06-13 14:16:19
不确定这是否是经济放缓的原因(你的个人资料是为了得到你的4倍的数字吗?)但是这个循环可能很慢:
for(int i = 0; i < vectorLength; i++)
{
a[i] = test(i);
}如果大部分时间用于处理代码中的循环,那么这个额外的循环可能会使时间加倍(并且与ublas无关)。我建议使用std::copy来代替:
std::copy(test.begin(), test.end(), a[0])大多数编译器应该看到这是复制一个双拷贝,并执行一个最优的复制,这可能在一定程度上解决了您的问题。
https://stackoverflow.com/questions/6330936
复制相似问题