内存映射C ++中的二进制日志记录

时间:2015-08-11 03:51:09

标签: c++

我需要获取一个结构并将其转储到一个文件中供以后使用。它需要尽可能快。

通过各种解决方案的实验,我得出的结论是memcpy()到内存映射(带有大页面)文件是解决问题的最快方法。有更好的方法吗?

我尝试过异步日志记录但是它 1.)充其量是同步存储器映射解决方案的最佳速度 2.)有一个额外线程的额外开销(我也受限于资源:)

2 个答案:

答案 0 :(得分:2)

以下是使用Boost.Interprocess的示例:

#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <fstream>
#include <string>

namespace ip = boost::interprocess;

struct example {
   int data;
   // etc.
};

const char * filename = "/path/to/file";
int main () {
   // Remove existing mapping
   ip::file_mapping::remove (filename);

   // Create file
   std::filebuf fb;
   fb.open(filename, std::ios_base::in | std::ios_base::out
                          | std::ios_base::trunc | std::ios_base::binary);
   fb.pubseekoff (sizeof (example)-1,  std::ios_base::beg);
   fb.sputc (0);

   // Map to file
   ip::file_mapping mapping (filename, ip::read_write);

   // map a region
   ip::mapped_region region (mapping, ip::read_write);

   // Get mapped address
   void *addr = region.get_address( );

   // copy struct to file
   example ex;
   memcpy (addr, &ex, sizeof (example));

   // flush to disk
   region.flush ();
}

要获取数据,请以相同的方式映射到文件(尽管可能只有read_only访问)。可能在这里杀死你的是刷新磁盘,这可能需要一段时间。

理想情况下,您应该尝试Tanzer's Answer中的映射文件版本和简单的iostream版本。在目标平台上测量两者的性能并选择最佳平台。

答案 1 :(得分:1)

您可以使用ifstream和ofstream类将对象作为二进制文件写入文件。

struct anyobj;

ofstream ofs("file.bin",ios::binary);
ofs.write ((char*) & anyobj , sizeof(anyobj));

然后阅读

struct anyobj2;

ifstream ifs ("file.bin", ios::binary);
ifs.read((char*) & anyobj2 , sizeof(anyobj2));

但是你应该注意不同系统(可移植性)和编译器(不同的填充策略)等情况。

相关问题