轉載請注明出處:http://blog.csdn.net/jmppok/article/details/18087685
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";
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;
uncompress(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;
}
}
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左右。解壓非常快。