有没有一种有效的方法可以删除已分配但空的本征行而无需重新分配?

时间:2019-05-29 09:54:04

标签: c++ performance reshape eigen memory-efficient

我正在尝试使用Eigen :: Matrix类编写运行时有效的代码。为了提高运行时间,我知道建议调整Eigen :: Matrix的大小,以便分配足够的内存,从而避免重新分配。但是,我不知道在编译时或在矩阵初始化时的行数。我要做的是使用动态大小的矩阵,以已知的上限分配内存,然后将一些数据填充到矩阵中,最后“切除/重塑”我不需要的低端行。

所以我的问题看起来像这样,除了我分配的内存远大于(5,3)

    Eigen::MatrixXi M;
    M.resize(5,3);
    std::cout << "M size: (" << M.rows() << "x" << M.cols()<< " ) with Entries:\n"<< M << std::endl;
    M.row(0) = Eigen::RowVector3i(1, 1, 1);
    M.row(1) = Eigen::RowVector3i(2, 2, 2);
    M.row(2) = Eigen::RowVector3i(3, 3, 3);
    //M.reshape(3, 3); ??
    std::cout << "M size: (" << M.rows() << "x" << M.cols() << " ) with Entries:\n" << M << std::endl;

我知道下面的代码可以工作,但是此代码片段包括重新分配新的内存,而不只是“释放” M的低行或重新映射M的内存;

    // works but inefficient
    Eigen::MatrixXi M2;
    M2.resize(3, 3);
    M2 = M.topRows(3);

您对我如何更有效地实施此想法有任何想法吗?

1 个答案:

答案 0 :(得分:0)

First of all, if you are adding entries row-by-row, it could be more efficient to use a row-major matrix. Also, if the number of columns is known at compile-time to be 3, you can express this in the type:

typedef Eigen::Matrix<int, Eigen::Dynamic, 3, Eigen::RowMajor> MatrixRX3i;
MatrixRX3i M;
M.resize(5,3);

If you don't mind that the entire memory of M is kept all the time, you can define M2 as an Eigen::Ref object:

Eigen::Ref<MatrixRX3i> M2(M.topRows(3));

If you want to deallocate unnecessary memory, you should use conservativeResize():

M.conservativeResize(3,3);

Ideally, this should just call std::realloc (in case the inner dimension does not change), though there might be some alignment related corner-cases.