如何读/写矢量<块*>作为内存映射文件?
How to read/write vector<Chunk*> as memory mapped file(s)?
我有一大组数据块(~50GB)。在我的代码中,我必须能够执行以下操作:
-
反复遍历所有块并对其进行一些计算。
-
反复迭代所有块并对其进行一些计算,在每次迭代中,访问块的顺序(尽可能)随机化。
到目前为止,我已经将数据拆分为 10 个二进制文件(使用 boost::serialization
创建),并反复读取一个接一个并执行计算。对于 (2),我以随机顺序读取 10 个文件并按顺序处理每个文件,这已经足够了。
但是,读取其中一个文件(使用 boost::serialization
)需要很长时间,我想加快速度。
我可以使用内存映射文件而不是boost::serialization
吗?
特别是,我会在每个文件中都有一个vector<Chunk*>
。我希望能够非常非常快速地读取这样的文件。
如何读/写这样vector<Chunk*>
的数据结构?我看过boost::interprocess::file_mapping
,但我不知道该怎么做。
我读了这个(http://boost.cowic.de/rc/pdf/interprocess.pdf),但它并没有说太多关于内存映射文件的信息。我想我会先将vector<Chunk*>
存储在映射的内存中,然后存储块本身。而且,vector<Chunk*>
实际上会变成offset_ptr<Chunk>*
,即offset_ptr数组?
内存映射文件是内存块,与任何其他内存一样,它可以以字节、小端数、位或任何其他数据结构进行组织。如果可移植性是一个问题(例如字节序),则需要小心。
以下代码可能是一个很好的起点:
#include <cstdint>
#include <memory>
#include <vector>
#include <iostream>
#include <boost/iostreams/device/mapped_file.hpp>
struct entry {
std::uint32_t a;
std::uint64_t b;
} __attribute__((packed)); /* compiler specific, but supported
in other ways by all major compilers */
static_assert(sizeof(entry) == 12, "entry: Struct size mismatch");
static_assert(offsetof(entry, a) == 0, "entry: Invalid offset for a");
static_assert(offsetof(entry, b) == 4, "entry: Invalid offset for b");
int main(void) {
boost::iostreams::mapped_file_source mmap("map");
assert(mmap.is_open());
const entry* data_begin = reinterpret_cast<const entry*>(mmap.data());
const entry* data_end = data_begin + mmap.size()/sizeof(entry);
for(const entry* ii=data_begin; ii!=data_end; ++ii)
std::cout << std::hex << ii->a << " " << ii->b << std::endl;
return 0;
}
data_begin和data_end指针可以像任何其他迭代器一样与大多数 STL 函数一起使用。
- 将字符串存储在c++中的稳定内存中
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- Win32编译器选项和内存分配
- 当vector是tje全局变量时,c++中vector的内存管理
- 带内存和隔离功能的SQLite
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 迭代时从向量和内存中删除对象
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 为什么示例代码访问IUnknown中已删除的内存
- 如何在C++类内存结构中创建"spacer"?
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 如何针对特定情况调试和修复此双自由内存损坏问题
- 类型总是使用其大小存储在内存中吗
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存