由于我们的大部分代码都是用C ++编写的,我想压缩/ 用同一种语言解压缩文件。我已经尝试过boost gzip库,但无法使其工作(不压缩):
int writeEventCollection(HEP::MyProtoBufClass* protobuf, std::string filename, unsigned int compressionLevel) {
ofstream file(filename.c_str(), ios_base::out | ios_base::binary);
filtering_streambuf<output> out;
out.push(gzip_compressor(compressionLevel));
out.push(file);
if (!protobuf->SerializeToOstream(&file)) {//serialising to wrong stream I asume
cerr << "Failed to write ProtoBuf." << endl;
return -1;
}
return 0;
}
我搜索了使用GzipOutputStream and GzipInputStream协议缓冲区的示例,但找不到工作 例。
正如你现在可能已经注意到的那样,我最初是一个初学者 并且非常感谢一个完整的例子 http://code.google.com/apis/protocolbuffers/docs/cpptutorial.html (我有我的address_book,如何将其保存在gziped文件中?)
提前谢谢你。
编辑:工作实例。
示例1遵循StackOverflow
上的答案int writeEventCollection(shared_ptr<HEP::EventCollection> eCollection,
std::string filename, unsigned int compressionLevel) {
filtering_ostream out;
out.push(gzip_compressor(compressionLevel));
out.push(file_sink(filename, ios_base::out | ios_base::binary));
if (!eCollection->SerializeToOstream(&out)) {
cerr << "Failed to write event collection." << endl;
return -1;
}
return 0;
}
示例2关于Google's Protobuf discussion group的回答:
int writeEventCollection2(shared_ptr<HEP::EventCollection>
eCollection, std::string filename,
unsigned int compressionLevel) {
using namespace google::protobuf::io;
int filedescriptor = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC,
S_IREAD | S_IWRITE);
if (filedescriptor == -1) {
throw "open failed on output file";
}
google::protobuf::io::FileOutputStream file_stream(filedescriptor);
GzipOutputStream::Options options;
options.format = GzipOutputStream::GZIP;
options.compression_level = compressionLevel;
google::protobuf::io::GzipOutputStream gzip_stream(&file_stream,
options);
if (!eCollection->SerializeToZeroCopyStream(&gzip_stream)) {
cerr << "Failed to write event collection." << endl;
return -1;
}
close(filedescriptor);
return 0;
}
对性能的一些评论(阅读当前格式和编写ProtoBuf 11146文件): 例1:
real 13m1.185s
user 11m18.500s
sys 0m13.430s
CPU usage: 65-70%
Size of test sample: 4.2 GB (uncompressed 7.7 GB, our current compressed format: 7.7 GB)
示例2:
real 12m37.061s
user 10m55.460s
sys 0m11.900s
CPU usage: 90-100%
Size of test sample: 3.9 GB
似乎Google的方法更有效地使用CPU,速度稍快(虽然我希望它在准确度范围内)并且使用相同的压缩设置生成约7%的小数据集。
答案 0 :(得分:3)
您的假设是正确的:您发布的代码不起作用,因为您直接写入ofstream
而不是filtering_streambuf
。为了完成这项工作,您可以改为使用filtering_ostream
:
ofstream file(filename.c_str(), ios_base::out | ios_base::binary);
filtering_ostream out;
out.push(gzip_compressor(compressionLevel));
out.push(file);
if (!protobuf->SerializeToOstream(&out)) {
// ... etc.
}
或者更简洁,使用file_sink
:
filtering_ostream out;
out.push(gzip_compressor(compressionLevel));
out.push(file_sink(filename, ios_base::out | ios_base::binary));
if (!protobuf->SerializeToOstream(&out)) {
// ... etc.
}
我希望这有帮助!