问题
I'm using Eigen with big matrices and I'm thinking about ways to optimize my code, focusing on reducing dynamic memory allocation.
I'm trying to multiply two matrices. Those matrices change a little bit every now and then, but their sizes stay the same.
I'd like to see the output of the multiplication going to a predefined matrix (that would have memory already allocated for it).
So here's an example of what I'm doing:
Eigen::MatrixXd left, right,result;
// ...
result = left * right;
// ... left and right values change a little
result = left * right;
And I'm looking for a solution that would be like that:
void Multiply(
Eigen::MatrixXd const& left,
Eigen::MatrixXd const& right,
Eigen::MatrixXd& result);
void Example()
{
Eigen::MatrixXd left, right, result;
// ...
Multiply(left, right, result);
// ...
Multiply(left, right, result);
}
The aim is basically to reuse the result
matrix memory because in theory it should not change dimension. I was thinking about using operator*=
but I kind of realize that it still needs an intermediate matrix to do the calculation.
回答1:
result = left * right
allocates a temporary matrix to hold the result of the multiplication, evaluates the product into the temporary matrix, and then copies the result from the temporary matrix to result
. This is to deal with statements like A = A * B
where a temporary matrix is needed.
If you know that the result is different from the matrices in the product, then you can write result.noalias() = left * right
. Eigen will not use a temporary matrix in this case.
More explanation on aliasing in Eigen is at http://eigen.tuxfamily.org/dox/group__TopicAliasing.html
来源:https://stackoverflow.com/questions/24259998/no-copy-multiplication-in-eigen