protobuf序列化存储

之前做的一个项目,为了提速,用到了序列化存储。

下面是一个protobuf的使用示例。

#include "person.pb.h"
#include "iostream"
#include "fstream"
#include "time.h"


#pragma comment(lib, "libprotobuf.lib")
#pragma comment(lib, "libprotobuf-lite.lib")
#pragma comment(lib, "libprotoc.lib")

namespace pf=google::protobuf;

int main(void)
{
	GOOGLE_PROTOBUF_VERIFY_VERSION;
	clock_t t1, t2, t3, t4, t5;
	//write into test_pb.dat
	t1 = clock();
	lm::m_pb_test t_msg;
	
	//t_msg.set_id(100);
	//t_msg.set_name("James Wang");

	for(int i=0; i<102400; i++)
	{
		t_msg.add_img(1.2f);
	}
	std::fstream out_file("../resource/test_pb.dat", std::ios::out | \
										std::ios::trunc | std::ios::binary);
	if(!t_msg.SerializeToOstream(&out_file))
	{
		std::cerr << "failed to write from t_msg" << std::endl;
		exit(-1);
	}
	out_file.close();
	t2 = clock();
	std::ofstream a("../resource/test.dat");
	for(int i=0; i<102400; i++)
	{
		a << 1.2f;
	}
	a.close();
	t3 = clock();
	//read from test_pb.dat
	lm::m_pb_test r_msg;
	std::fstream in_file("../resource/test_pb.dat", std::ios::in | std::ios::binary);

	if(!r_msg.ParseFromIstream(&in_file))
	{
		std::cerr << "failed to read to r_msg" << std::endl;
		exit(-1);
	}
	
	//std::cout << r_msg.id() <::const_iterator iter=r_msg.img().begin(); \
		iter != r_msg.img().end(); iter++)
	{
		std::cout << *iter << " ";
	}
	std::cout << std::endl;

	pf::ShutdownProtobufLibrary();
	t4 = clock();
	std::ifstream in("../resource/test.dat");
	if (!in.is_open())
	{
		std::cout << "File open error!\n";
		return -1;
	}
	float c;
	while(!in.eof())
	{
		in >> c;
	}
	in.close();
	t5 = clock();

	std::cout << "pb write time: " << (double)(t2-t1)/CLOCKS_PER_SEC << std::endl;
	std::cout << "normal write time: " << (double)(t3-t2)/CLOCKS_PER_SEC << std::endl;
	std::cout << "pb read time: " << (double)(t4-t3)/CLOCKS_PER_SEC << std::endl;
	std::cout << "normal read time: " << (double)(t5-t4)/CLOCKS_PER_SEC << std::endl;

	system("pause");

	return 0;
}


当然,实际使用时还有一些配置问题。

到时候可自行搜索。



你可能感兴趣的:(protobuf序列化存储)