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

前端之家收集整理的这篇文章主要介绍了c – 特征和巨大的密集2D阵列前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在为项目使用2D Eigen :: Arrays,我喜欢在巨大的2D数组的情况下继续使用它们.

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

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

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

编辑:

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

  1. #include <Eigen/Dense>
  2.  
  3.  
  4. int main()
  5. {
  6. // Order of magnitude of the required arrays
  7. Eigen::Index rows = 50000;
  8. Eigen::Index cols = 40000;
  9.  
  10. {
  11. // Array creation (this is where the memory mapped file should be created)
  12. Eigen::ArrayXXf arr1 = Eigen::ArrayXXf::Zero( rows,cols );
  13.  
  14. // Some operations on the array
  15. for(Eigen::Index i = 0; i < rows; ++i)
  16. {
  17. for(Eigen::Index j = 0; j < cols; ++j)
  18. {
  19. arr1( i,j ) = float(i * j);
  20. }
  21. }
  22.  
  23. // The array goes out of scope,but the data are persistently stored in the file
  24. }
  25.  
  26. {
  27. // This should actually use the data stored in the file
  28. Eigen::ArrayXXf arr2 = Eigen::ArrayXXf::Zero( rows,cols );
  29.  
  30. // Manipulation of the array data
  31. for(Eigen::Index i = 0; i < rows; ++i)
  32. {
  33. for(Eigen::Index j = 0; j < cols; ++j)
  34. {
  35. arr2( i,j ) += 1.0f;
  36. }
  37. }
  38.  
  39. // The array goes out of scope,but the data are persistently stored in the file
  40. }
  41.  
  42. }

解决方法

所以我用Google搜索

boost memory mapped file

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

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

  1. #include <boost/iostreams/device/mapped_file.hpp>
  2. #include <Eigen/Dense>
  1. boost::iostreams::mapped_file file("foo.bin");
  2.  
  3. const std::size_t rows = 163840;
  4. const std::size_t columns = 163840;
  5. if (rows * columns * sizeof(float) > file.size()) {
  6. 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));
  7. }
  8.  
  9. Eigen::Map<Eigen::MatrixXf> matrix(reinterpret_cast<float*>(file.data()),rows,columns);
  10.  
  11. std::cout << matrix(0,0) << ' ' << matrix(rows - 1,columns - 1) << std::endl;
  12. matrix(0,0) = 0.5;
  13. matrix(rows - 1,columns - 1) = 0.5;

使用cmake

  1. find_package(Boost required COMPONENTS iostreams)
  2. find_package(Eigen3 required)
  3. target_link_libraries(${PROJECT_NAME} Boost::iostreams Eigen3::Eigen)

然后我用Google搜索

windows create dummy file

first result给了我

  1. fsutil file createnew foo.bin 107374182400

两次运行程序给出:

0 0

0.5 0.5

没有炸毁内存使用情况.

所以它就像一个魅力.

猜你在找的C&C++相关文章