基于Snappy实现数据压缩和解压

Snappy是谷歌开源的一个用来压缩和解压的开发包。相较其他压缩算法速率有明显的优势,官方文档显示在64位 i7处理器上,每秒可达200~500MB的压缩速度,不禁感叹大厂的算法就是厉害。

开源项目地址:https://github.com/google/snappy

开撸

1.下载最新版本Snappy 1.1.7,下载地址如下:

https://github.com/google/snappy/releases

2.解压:

tar -zxvf tar -zxvf snappy-1.1.7.tar.gz

3.进入该目录

cd snappy-1.1.7

4.创建build目录

mkdir build

5.本机需要安装cmake工具,版本>=3.1。执行cmake

cd build & cmake ../

6.编译

make

build目录下回生成静态库libsnappy.a,所需头文件snappy-stubs-public.h和根目录下的snappy.h。

有了库文件和两个头文件,可以使用了。

新建snappy-test目录,把库文件libsnappy.a,snappy.h,snappy-stubs-public.h三个文件放到该目录下新建main.cpp文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include "snappy.h"
#include <string.h>

using namespace std;

int main()
{
string input = "i love china!";
for(int i=0; i<5; i++)
{
input += input;
}
cout << "压缩前:" << input.size() << endl;
cout << input << endl;
cout << "=================================" << endl;
string output = "";
snappy::Compress(input.data(), input.size(), &output);

cout << "压缩后:" << output.size() << endl;
cout << output << endl;
cout << "=================================" << endl;

string str = "";
snappy::Uncompress(output.data(), output.size(), &str);
cout << "解压后:" << str.size() << endl;
cout << str << endl;
return 1;
}

运行结果:

压缩前416字节,压缩后37字节。

不想编译库的可以直接下载:

关注下面公众号,回复”108”获取snappy-windows源码

关注下面公众号,回复”109”获取snappy-linux源码

# Snappy

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×