使用gzip_compressor生成不同的文件大小

Using gzip_compressor yield different file sizes

本文关键字:文件大小 gzip compressor 使用      更新时间:2023-10-16

我使用gzip_compressor()来压缩输出文件。为此我使用了两种方法。共有部分为

std::ofstream traceOut;
traceOut.open("log.gz", std::ios_base::out);
struct traceRec {
  traceRec(uint64_t c) : cycle(c) {};
  uint64_t cycle;
};
void writeTrace(traceRec &rec)
{
  boost::iostreams::filtering_ostream o;
  o.push(boost::iostreams::gzip_compressor());
  o.push(traceOut);
  // METHOD 1 OR 2
}

方法1

我使用

 o.write(reinterpret_cast<const char*>(&rec.cycle), sizeof(rec.cycle));

使用此实现,文件大小为380K!!

方法2

我使用

 traceOut << rec.cycle << std::endl;

使用此实现,文件大小为78K!!

那为什么它们的大小不同呢??另外,如果我不使用gzip_compressor直接写入文件

std::ofstream traceOut;
traceOut.open("log.gz", std::ios_base::out);
...
traceOut << rec.cycle << std::endl;

文件大小为78K。

所以有两个问题:

1-使用或不使用gzip_compressor对文件大小没有影响

2-使用gzip_compressor的不同实现产生不同的文件大小

你知道吗?

operator <<可能使用数字的文本表示形式,而write方法采用完整的可变大小。

例如,如果你有一个"13"的循环,在"写"的情况下,你将消耗8个字节,而在文本表示中你只消耗2个字节。

当压缩时,效果更加显著,因为当将数字作为文本时,只使用10个字符,(非常非常低的熵),所以它是高度冗余和可压缩的。

另一方面,如果循环计数器通常非常大(> 99999999),那么write方法将提供更好的压缩。