天天看點

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/

繼續閱讀