我正在寻找一种非常快速的 C++ 二进制序列化技术。我只需要序列化对象中包含的数据(没有指针等)。我希望它尽可能快。如果它特定于 x86 硬件,这是可以接受的。
我熟悉执行此操作的 C 方法。作为测试,我对几种技术进行了基准测试。我发现 C 方法比我实现的最佳 C++ 方法快 40%。
关于如何改进 C++ 方法(或执行此操作的库)有什么建议吗?有什么好的内存映射文件可用吗?
// c style writes
{
#pragma pack(1)
struct item
{
uint64_t off;
uint32_t size;
} data;
#pragma pack
clock_t start = clock();
FILE* fd = fopen( "test.c.dat", "wb" );
for ( long i = 0; i < tests; i++ )
{
data.off = i;
data.size = i & 0xFFFF;
fwrite( (char*) &data, sizeof(data), 1, fd );
}
fclose( fd );
clock_t stop = clock();
double d = ((double)(stop-start))/ CLOCKS_PER_SEC;
printf( "%8.3f seconds\n", d );
}
测试约 1.6 秒 = 10000000
// c++ style ofstream writes
// define a DTO class
class test
{
public:
test(){}
uint64_t off;
uint32_t size;
friend std::ostream& operator<<( std::ostream& stream, const test& v );
};
// write to the stream
std::ostream& operator<<( std::ostream &stream, const test& v )
{
stream.write( (char*)&v.off, sizeof(v.off) );
stream.write( (char*)&v.size, sizeof(v.size) );
return stream;
}
{
test data;
clock_t start = clock();
std::ofstream out;
out.open( "test.cpp.dat", std::ios::out | std::ios::trunc | std::ios::binary );
for ( long i = 0; i < tests; i++ )
{
data.off = i;
data.size = i & 0xFFFF;
out << data;
}
out.close();
clock_t stop = clock();
double d = ((double)(stop-start))/ CLOCKS_PER_SEC;
printf( "%8.3f seconds\n", d );
}
测试约 2.6 秒 = 10000000