msgpack[C++]使用笔记 和 msgpack/cPickle性能对比

python版本msgpack安装:

wget http://pypi.python.org/packages/source/m/msgpack-python/msgpack-python-0.1.9.tar.gz

python2.x setup.py install --prefix=/usr/local/similarlib/


python版本的msgpack灰常好用,速度上比python内置的pickle和cpickle都要快一些,C++版本的使用比较麻烦,下面是本人学习时的一个demo,解析python-msgpack dump的一个复杂字典

#include <msgpack.hpp>

#include <fstream>
#include <iostream>
using namespace std;

template <class T>
void msgunpack(const char* binary_file, T& t, char* buff, uint32_t max){
	msgpack::unpacked msg;
	ifstream tf_file(binary_file,ios::in|ios::binary|ios::ate);
	uint32_t size = tf_file.tellg();
	tf_file.seekg(0, ios::beg);
	tf_file.read(buff, size);
	tf_file.close();
	msgpack::unpack(&msg, buff, size);
	msg.get().convert(&t);
}


typedef map<uint32_t, uint32_t> WordsMap;
typedef map<uint32_t, WordsMap> FieldsMap;
typedef map<uint64_t, FieldsMap> DocsMap;

int main(int argc, char** argv)
{
	uint32_t MAX_BUFF = 1024*1024*100; //100MB
	char* BUFF = new char[MAX_BUFF];

	DocsMap docsMap;
	msgpack::unpacked msg;
	msgunpack("/data/wikidoc/tf_dict_for_nodes/1-1000", docsMap, BUFF, MAX_BUFF);
	//        msg.get().convert(&docsMap);
	cout << docsMap.size() << endl;
        delete[] BUFF;
}



参考: http://wiki.msgpack.org/pages/viewpage.action?pageId=1081387#QuickStartforC%2B%2B-ImplementationStatus


下面是本人自己封装的一个msgpack接口头文件mymsgpack.h

 #ifndef MY_MSGPACK_H

#ifndef MY_MSGPACK_H
#define MY_MSGPACK_H
#include <fstream>
#include <msgpack.hpp>
using namespace std;

template <class T>
void load_from_file(const char* binary_file, T& t) {
        ifstream binaryFstream(binary_file,ios::in|ios::binary|ios::ate);
        uint32_t size = binaryFstream.tellg();
        char* buff = new char[size];
        binaryFstream.seekg(0, ios::beg);
        binaryFstream.read(buff, size);
        binaryFstream.close();
        msgpack::unpacked msg;
        msgpack::unpack(&msg, buff, size);
        msg.get().convert(&t);
        delete[] buff;
}

template <class T>
void load_from_str(const char* binary_str, int len, T& t) {
        msgpack::unpacked msg;
        msgpack::unpack(&msg, binary_str, len);
        msg.get().convert(&t);
}

template <class T>
void dump_to_file(T& t, const char* dump_file) {
	msgpack::sbuffer sbuf;
	msgpack::pack(sbuf, t);
	ofstream dumpFstream(dump_file, ios::out|ios::binary|ios::trunc);
	dumpFstream.write(sbuf.data(), sbuf.size());
	dumpFstream.close();
}

template <class T>
void dump_to_str(T& t, char** dump_str, int& len) { //外部释放*dump_str
	msgpack::sbuffer sbuf;
	msgpack::pack(sbuf, t);
	len = sbuf.size();
	*dump_str = (char*)malloc(sbuf.size());
	memcpy(*dump_str, sbuf.data(), sbuf.size());
}

#endif


 


msgpack编译通过,链接不上的问题 undefined reference to `__sync_sub_and_fetch_4'

在x84_64机器上正常,在32bit机器上出现上述问题

[xudongsong@BigServerU-4 msgpack-0.5.7]$ cat /etc/issue
CentOS release 5.4 (Final)
Kernel \r on an \m

[xudongsong@BigServerU-4 msgpack-0.5.7]$ file /sbin/init
/sbin/init: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.6.9, dynamically linked (uses shared libs), for GNU/Linux 2.6.9, stripped

./configure不报错,但是查看config.log显示有错误,程序链接msgpack的库时也报错

原因:gcc不能识别CPU体系,需要手动指明

[xudongsong@BigServerU-4 msgpack-0.5.7]$ CFLAGS="-march=pentium -mtune=pentium" ./configure --prefix=/home/xudongsong/msgpack_static --enable-static=yes --enable-shared=no

make, make install

[xudongsong@BigServerU-4 jobs]$ g++ job_calc_weight.cpp -o job_calc_weight -I/home/xudongsong/msgpack_static/include/ -L/home/xudongsong/msgpack_static/lib/ -lmsgpack

通过!

 


 

下面是msgpack和cPickle进行性能pk的demo程序(不比较pickle,是因为它比cPickle更慢,《Python cook book》里面有说明):

mport sys,time,msgpack,pickle,cPickle,random

test_list = []
i = 0
while i<100000:
	test_list = random.randrange(1,100000)
	i += 1

print "common len(serialize) = %s"%len(cPickle.dumps(test_list,0))
print "compress len(serialize) = %s"%len(cPickle.dumps(test_list,1))

#------------------------------------------------------------------------
results = {}
time_start = time.time()
for i in range(1,1000000):
        results[i] = cPickle.dumps(test_list,1)
time_mid_1 = time.time()
print "cPickle dumps eats %s s"%str(time_mid_1-time_start)

for i in range(1,1000000):
	cPickle.loads(results[i])
time_mid_2 = time.time()
print "cPickle loads eats %s s"%str(time_mid_2-time_mid_1)

#------------------------------------------------------------------------
results = {}
time_start = time.time()
for i in range(1,1000000):
	results[i] = msgpack.dumps(test_list)
time_mid_1 = time.time()
print "msgpack pack eats %s s"%str(time_mid_1-time_start)

for i in range(1,1000000):
	msgpack.loads(results[i])
time_mid_2 = time.time()
print "msgpack unpack eats %s s"%str(time_mid_2-time_mid_1)



 


 

/home/AQTJClient/AQTJAuditClient/depends/msgpack-c-master/include/msgpack/v1/object.hpp:664:34: error: ‘void* memcpy(void*, const void*, size_t)’ copying an object of non-trivial type ‘struct msgpack::v2::object’ from an array of ‘const msgpack_object’ {aka ‘const struct msgpack_object’} [-Werror=class-memaccess] std::memcpy(&o, &v, sizeof(v)); ^ In file included from /home/AQTJClient/AQTJAuditClient/depends/msgpack-c-master/include/msgpack/object_fwd.hpp:17, from /home/AQTJClient/AQTJAuditClient/depends/msgpack-c-master/include/msgpack/v1/adaptor/adaptor_base_decl.hpp:14, from /home/AQTJClient/AQTJAuditClient/depends/msgpack-c-master/include/msgpack/adaptor/adaptor_base_decl.hpp:13, from /home/AQTJClient/AQTJAuditClient/depends/msgpack-c-master/include/msgpack/adaptor/adaptor_base.hpp:13, from /home/AQTJClient/AQTJAuditClient/depends/msgpack-c-master/include/msgpack/v1/object_decl.hpp:16, from /home/AQTJClient/AQTJAuditClient/depends/msgpack-c-master/include/msgpack/object_decl.hpp:14, from /home/AQTJClient/AQTJAuditClient/depends/msgpack-c-master/include/msgpack/object.hpp:13, from /home/AQTJClient/AQTJAuditClient/depends/msgpack-c-master/include/msgpack.hpp:10, from /home/AQTJClient/AQTJAuditClient/depends/msgpack-c-master/example/cpp03/stream.cpp:10: /home/AQTJClient/AQTJAuditClient/depends/msgpack-c-master/include/msgpack/v2/object_fwd.hpp:23:8: note: ‘struct msgpack::v2::object’ declared here struct object : v1::object { ^~~~~~ cc1plus: all warnings being treated as errors make[2]: *** [example/cpp03/CMakeFiles/stream.dir/build.make:63:example/cpp03/CMakeFiles/stream.dir/stream.cpp.o] 错误 1 make[2]: 离开目录“/home/AQTJClient/AQTJAuditClient/depends/msgpack-c-master” make[1]: *** [CMakeFiles/Makefile2:415:example/cpp03/CMakeFiles/stream.dir/all] 错误 2 make[1]: 离开目录“/home/AQTJClient/AQTJAuditClient/depends/msgpack-c-master”
07-20
======================= MessagePack for Python ======================= :author: INADA Naoki :version: 0.4.1 :date: 2014-02-17 .. image:: https://secure.travis-ci.org/msgpack/msgpack-python.png :target: https://travis-ci.org/#!/msgpack/msgpack-python What's this ------------ `MessagePack <http://msgpack.org/>`_ is a fast, compact binary serialization format, suitable for similar data to JSON. This package provides CPython bindings for reading and writing MessagePack data. Install --------- You can use ``pip`` or ``easy_install`` to install msgpack:: $ easy_install msgpack-python or $ pip install msgpack-python PyPy ^^^^^ msgpack-python provides pure python implementation. PyPy can use this. Windows ^^^^^^^ When you can't use binary distribution, you need to install Visual Studio or Windows SDK on Windows. (NOTE: Visual C++ Express 2010 doesn't support amd64. Windows SDK is recommanded way to build amd64 msgpack without any fee.) Without extension, using pure python implementation on CPython runs slowly. Notes ----- Note for msgpack 2.0 support ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ msgpack 2.0 adds two types: *bin* and *ext*. *raw* was bytes or string type like Python 2's ``str``. To distinguish string and bytes, msgpack 2.0 adds *bin*. It is non-string binary like Python 3's ``bytes``. To use *bin* type for packing ``bytes``, pass ``use_bin_type=True`` to packer argument. >>> import msgpack >>> packed = msgpack.packb([b'spam', u'egg'], use_bin_type=True) >>> msgpack.unpackb(packed, encoding='utf-8') ['spam', u'egg'] You shoud use it carefully. When you use ``use_bin_type=True``, packed binary can be unpacked by unpackers supporting msgpack-2.0. To use *ext* type, pass ``msgpack.ExtType`` object to packer. >>> import msgpack >>> packed = msgpack.packb(msgpack.ExtType(42, b'xyzzy')) >>> msgpack.unpackb(packed) ExtType(code=42, data='xyzzy') You can use it with ``default`` and ``ext_hook``. See below. Note for msgpack 0.2.x users ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The msgpack 0.3 have some incompatible changes. The default value of ``use_list`` keyword argument is ``True`` from 0.3. You should pass the argument explicitly for backward compatibility. `Unpacker.unpack()` and some unpack methods now raises `OutOfData` instead of `StopIteration`. `StopIteration` is used for iterator protocol only. How to use ----------- One-shot pack & unpack ^^^^^^^^^^^^^^^^^^^^^^ Use ``packb`` for packing and ``unpackb`` for unpacking. msgpack provides ``dumps`` and ``loads`` as alias for compatibility with ``json`` and ``pickle``. ``pack`` and ``dump`` packs to file-like object. ``unpack`` and ``load`` unpacks from file-like object. :: >>> import msgpack >>> msgpack.packb([1, 2, 3]) '\x93\x01\x02\x03' >>> msgpack.unpackb(_) [1, 2, 3] ``unpack`` unpacks msgpack's array to Python's list, but can unpack to tuple:: >>> msgpack.unpackb(b'\x93\x01\x02\x03', use_list=False) (1, 2, 3) You should always pass the ``use_list`` keyword argument. See performance issues relating to use_list_ below. Read the docstring for other options. Streaming unpacking ^^^^^^^^^^^^^^^^^^^ ``Unpacker`` is a "streaming unpacker". It unpacks multiple objects from one stream (or from bytes provided through its ``feed`` method). :: import msgpack from io import BytesIO buf = BytesIO() for i in range(100): buf.write(msgpack.packb(range(i))) buf.seek(0) unpacker = msgpack.Unpacker(buf) for unpacked in unpacker: print unpacked Packing/unpacking of custom data type ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ It is also possible to pack/unpack custom data types. Here is an example for ``datetime.datetime``. :: import datetime import msgpack useful_dict = { "id": 1, "created": datetime.datetime.now(), } def decode_datetime(obj): if b'__datetime__' in obj: obj = datetime.datetime.strptime(obj["as_str"], "%Y%m%dT%H:%M:%S.%f") return obj def encode_datetime(obj): if isinstance(obj, datetime.datetime): return {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f")} return obj packed_dict = msgpack.packb(useful_dict, default=encode_datetime) this_dict_again = msgpack.unpackb(packed_dict, object_hook=decode_datetime) ``Unpacker``'s ``object_hook`` callback receives a dict; the ``object_pairs_hook`` callback may instead be used to receive a list of key-value pairs. Extended types ^^^^^^^^^^^^^^^ It is also possible to pack/unpack custom data types using the msgpack 2.0 feature. >>> import msgpack >>> import array >>> def default(obj): ... if isinstance(obj, array.array) and obj.typecode == 'd': ... return msgpack.ExtType(42, obj.tostring()) ... raise TypeError("Unknown type: %r" % (obj,)) ... >>> def ext_hook(code, data): ... if code == 42: ... a = array.array('d') ... a.fromstring(data) ... return a ... return ExtType(code, data) ... >>> data = array.array('d', [1.2, 3.4]) >>> packed = msgpack.packb(data, default=default) >>> unpacked = msgpack.unpackb(packed, ext_hook=ext_hook) >>> data == unpacked True Advanced unpacking control ^^^^^^^^^^^^^^^^^^^^^^^^^^ As an alternative to iteration, ``Unpacker`` objects provide ``unpack``, ``skip``, ``read_array_header`` and ``read_map_header`` methods. The former two read an entire message from the stream, respectively deserialising and returning the result, or ignoring it. The latter two methods return the number of elements in the upcoming container, so that each element in an array, or key-value pair in a map, can be unpacked or skipped individually. Each of these methods may optionally write the packed data it reads to a callback function: :: from io import BytesIO def distribute(unpacker, get_worker): nelems = unpacker.read_map_header() for i in range(nelems): # Select a worker for the given key key = unpacker.unpack() worker = get_worker(key) # Send the value as a packed message to worker bytestream = BytesIO() unpacker.skip(bytestream.write) worker.send(bytestream.getvalue()) Note about performance ------------------------ GC ^^ CPython's GC starts when growing allocated object. This means unpacking may cause useless GC. You can use ``gc.disable()`` when unpacking large message. `use_list` option ^^^^^^^^^^^^^^^^^^ List is the default sequence type of Python. But tuple is lighter than list. You can use ``use_list=False`` while unpacking when performance is important. Python's dict can't use list as key and MessagePack allows array for key of mapping. ``use_list=False`` allows unpacking such message. Another way to unpacking such object is using ``object_pairs_hook``. Test ---- MessagePack uses `pytest` for testing. Run test with following command: $ py.test .. vim: filetype=rst
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值