我正在为项目使用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 comment到Eigen::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
然后我用Google搜索
windows create dummy file
而first result给了我
- fsutil file createnew foo.bin 107374182400
两次运行程序给出:
0 0
0.5 0.5
没有炸毁内存使用情况.
所以它就像一个魅力.