c – 特征和巨大的密集2D阵列

我正在为项目使用2D Eigen :: Arrays,我喜欢在巨大的2D数组的情况下继续使用它们.

为了避免内存问题,我想使用内存映射文件来管理(读/修改/写入)这些数组,但我找不到工作示例.

我发现的最接近的例子是基于boost :: interprocess的this,但它使用共享内存(而我更喜欢持久存储).

缺乏示例让我担心是否有更好的主流替代解决方案来解决我的问题.是这样的吗?一个最小的例子非常方便.

编辑:

这是在评论中解释我的用例的最小示例:

#include <Eigen/Dense>


int main()
{
    // Order of magnitude of the required arrays
    Eigen::Index rows = 50000;
    Eigen::Index cols = 40000;

    {
        // Array creation (this is where the memory mapped file should be created)
        Eigen::ArrayXXf arr1 = Eigen::ArrayXXf::Zero( rows,cols );

        // Some operations on the array
        for(Eigen::Index i = 0; i < rows; ++i)
        {
            for(Eigen::Index j = 0; j < cols; ++j)
            {
                arr1( i,j ) = float(i * j);
            }
        }

        // The array goes out of scope,but the data are persistently stored in the file
    }

    {
        // This should actually use the data stored in the file
        Eigen::ArrayXXf arr2 = Eigen::ArrayXXf::Zero( rows,cols );

        // Manipulation of the array data
        for(Eigen::Index i = 0; i < rows; ++i)
        {
            for(Eigen::Index j = 0; j < cols; ++j)
            {
                arr2( i,j ) += 1.0f;
            }
        }

        // The array goes out of scope,but the data are persistently stored in the file
    }

}

解决方法

所以我用Google搜索

boost memory mapped file

在第一个结果中出现了boost::iostreams::mapped_file.

结合从this commentEigen::Map链接,我测试了以下内容

#include <boost/iostreams/device/mapped_file.hpp>
#include <Eigen/Dense>
boost::iostreams::mapped_file file("foo.bin");

const std::size_t rows = 163840;
const std::size_t columns = 163840;
if (rows * columns * sizeof(float) > file.size()) {
    throw std::runtime_error("file of size " + std::to_string(file.size()) + " Couldn’t fit float Matrix of " + std::to_string(rows) + "×"  + std::to_string(columns));
}

Eigen::Map<Eigen::MatrixXf> matrix(reinterpret_cast<float*>(file.data()),rows,columns);

std::cout << matrix(0,0) << ' ' << matrix(rows - 1,columns - 1) << std::endl;
matrix(0,0) = 0.5;
matrix(rows - 1,columns - 1) = 0.5;

使用cmake

find_package(Boost required COMPONENTS iostreams)
find_package(Eigen3 required)
target_link_libraries(${PROJECT_NAME} Boost::iostreams Eigen3::Eigen)

然后我用Google搜索

windows create dummy file

first result给了我

fsutil file createnew foo.bin 107374182400

两次运行程序给出:

0 0

0.5 0.5

没有炸毁内存使用情况.

所以它就像一个魅力.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...