本征中没有副本乘法 [英] No copy multiplication in Eigen

查看:61
本文介绍了本征中没有副本乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Eigen用于大型矩阵,并且我正在考虑优化代码的方法,重点在于减少动态内存分配。

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);
  }

目标基本上是重用结果矩阵内存,因为从理论上讲它不应更改尺寸。我当时在考虑使用 operator * = ,但我有点意识到它仍然需要一个中间矩阵来进行计算。

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.

推荐答案

result = left * right 分配一个临时矩阵来保存乘法结果,并将乘积评估为临时矩阵,然后将结果从临时矩阵复制到结果。这是为了处理类似 A = A * B 的语句,其中需要一个临时矩阵。

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.

如果您知道结果与产品中的矩阵不同,则可以编写 result.noalias()= left * right 。在这种情况下,Eigen将不使用临时矩阵。

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.

有关Eigen中的别名的更多说明,请参见 http://eigen.tuxfamily.org/dox/group__TopicAliasing.html

More explanation on aliasing in Eigen is at http://eigen.tuxfamily.org/dox/group__TopicAliasing.html

这篇关于本征中没有副本乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆