天天看点

zlib使用与性能测试

  1.下载编译

  可以从zlib官网下载:http://www.zlib.net/

  下载后直接make既可。make后再目录下生成libz.a.

  2.使用

  引用zlib.h和libz.a既可。关键在于zlib.h,它提供了一些函数。

  以下是引自“http://www.cppblog.com/woaidongmao/archive/2009/09/07/95495.html”的关于zlib.h的说明:

  都在zlib.h中,看到一堆宏不要晕,其实都是为了兼容各种编译器和一些类型定义.死死抓住那些主要的函数的原型声明就不会受到这些东西的影响了.

  关键的函数有那么几个:

  (1)int compress (bytef *dest,   ulongf *destlen, const bytef *source, ulong sourcelen);

  把源缓冲压缩成目的缓冲, 就那么简单, 一个函数搞定

  (2) int compress2 (bytef *dest,   ulongf *destlen,const bytef *source, ulong sourcelen,int level);

  功能和上一个函数一样,都一个参数可以指定压缩质量和压缩数度之间的关系(0-9)不敢肯定这个参数的话不用太在意它,明白一个道理就好了: 要想得到高的压缩比就要多花时间

  (3) ulong compressbound (ulong sourcelen);

  计算需要的缓冲区长度. 假设你在压缩之前就想知道你的产度为 sourcelen 的数据压缩后有多大, 可调用这个函数计算一下,这个函数并不能得到精确的结果,但是它可以保证实际输出长度肯定小于它计算出来的长度

  (4) int uncompress (bytef *dest,   ulongf *destlen,const bytef *source, ulong sourcelen);

  解压缩(看名字就知道了:)

  (5) deflateinit() + deflate() + deflateend()

  3个函数结合使用完成压缩功能,具体用法看 example.c 的 test_deflate()函数. 其实 compress() 函数内部就是用这3个函数实现的(工程 zlib 的 compress.c 文件)

  (6) inflateinit() + inflate() + inflateend()

  和(5)类似,完成解压缩功能.

  (7) gz开头的函数.用来操作*.gz的文件,和文件stdio调用方式类似. 想知道怎么用的话看example.c 的 test_gzio() 函数,很easy.

  (8) 其他诸如获得版本等函数就不说了.

  总结:其实只要有了compress() 和uncompress() 两个函数,在大多数应用中就足够了. 3.性能测试

  针对1m数据分别调用compress压缩和uncompress解压缩,循环10次。

  代码如下:

#include <stdio.h>

#include <time.h>

#include "zlib.h"

const int max_buffer_size = 1024*1024*4;

unsigned char data_buffer[max_buffer_size];

void testcompress()

{

const char * file = "/tmp/e2.txt.backup";

file *f1 = fopen(file,"r");

if(f1)

fseek(f1,0,2);

int len = ftell(f1);

fseek(f1,0,0);

char * data = new char[len];

fread(data,1,len,f1);

fclose(f1);

//ulong dst_len = max_buffer_size;

//bytef * dst = (bytef*)data_buffer;

clock_t start = clock();

for(int i=0; i<10; i++)

ulong dst_len = max_buffer_size;

bytef * dst = (bytef*)data_buffer;

compress(dst,&dst_len,(bytef *)data,(ulong)len);

}

clock_t end = clock();

printf("time used(ms):%.2f\n",1000.0*(end-start)/clocks_per_sec);

delete [] data;

void testuncompress()

const char * file = "/tmp/2.gz";

uncompress(dst,&dst_len,(bytef *)data,(ulong)len);

int main(int argc, char **argv)

testcompress();

testuncompress();

return 0;

  测试结果:

time used(ms):470.00

time used(ms):40.00

  4.总结

  zlib压缩1m数据耗时47ms左右,解压缩4ms左右。解压非常快。

最新内容请见作者的github页:http://qaseven.github.io/

继续阅读