轉載自:http://blog.csdn.net/sunny3106/article/details/7375907
在網絡程序的開發中,免不了會涉及到服務器與客戶端之間的協議交互,由于客戶端與服務器端的平臺的差異性(有可能是windows,android,linux等等),以及網絡字節序等問題,通信包一般會做序列化與反序列化的處理,也就是通常說的打包解包工作。google的protobuf是一個很棒的東西,它不僅提供了多平臺的支持,而且直接支持從配置文件生成代碼。但是這么強大的功能,意味著它的代碼量以及編譯生成的庫文件等等都不會小,如果相對于手機游戲一兩M的安裝包來說,這個顯然有點太重量級了(ps:查了一下protobuf2.4.1的jar的包大小有400k左右),而且在手機游戲客戶端與服務器的交互過程中,很多時候基本的打包解包功能就足夠了。
今天經同事推薦,查閱了一下msgpack相關的資料。msgpack提供快速的打包解包功能,官網上給出的圖號稱比protobuf快4倍,可以說相當高效了。最大的好處在與msgpack支持多語言,服務器端可以用C++,android客戶端可以用java,能滿足實際需求。
在實際安裝msgpack的過程中,碰到了一點小問題,因為開發機器是32位機器,i686的,所以安裝完后跑一個簡單的sample時,c++編譯報錯,錯誤的表現為鏈接時報錯:undefined reference to `__sync_sub_and_fetch_4',后來參考了下面的博客,在configure時指定CFLAGS="-march=i686"解決,注意要make clean先。
msgpack官網地址:http://msgpack.org/
安裝過程中參考的博客地址:http://blog.csdn.net/xiarendeniao/article/details/6801338
====================================================================================
====================================================================================
補上近期簡單的測試結果
測試機器,cpu 4核 Dual-Core AMD Opteron(tm) Processor 2212,單核2GHz,1024KB cache, 內存4G。
1. 簡單包測試
- struct ProtoHead
- {
- uint16_t uCmd;
- uint16_t uBodyLen;
- uint32_t uSeq;
- uint32_t uCrcVal;
- };
-
- struct ProtoBody
- {
- int num;
- std::string str;
- std::vector<uint64_t> uinlst;
- MSGPACK_DEFINE(num, str, uinlst);
- };
測試中省略了包頭本地字節序與網絡字節序之間的轉化,只有包體做msgpack打包處理.
vector數組中元素數量為16個,每次循環做一次打包與解包,并驗證前后數據是否一致,得到的測試結果如下:
總耗時(s) |
循環次數 |
平均每次耗時(ms) |
0.004691 |
100 |
0.04691 |
0.044219 |
1000 |
0.044219 |
0.435725 |
10000 |
0.043573 |
4.473818 |
100000 |
0.044738 |
總結:基本每次耗時0.045ms左右,每秒可以打包解包22k次,速度很理想。
2. 復雜包測試(vector嵌套)
- struct test_node
- {
- std::string str;
- std::vector<uint32_t> idlst;
-
- test_node()
- {
- str = "it's a test node";
-
- for (int i = 0; i++; i < 10)
- {
- idlst.push_back(i);
- }
- }
-
- bool operator == (const test_node& node) const
- {
- if (node.str != str)
- {
- return false;
- }
-
- if (node.idlst.size() != idlst.size())
- {
- return false;
- }
-
- for (int i = 0; i < idlst.size(); i++)
- {
- if (idlst[i] != node.idlst[i])
- {
- return false;
- }
- }
- return true;
- }
-
- MSGPACK_DEFINE(str, idlst);
- };
-
- struct ProtoBody
- {
- int num;
- std::string str;
- std::vector<uint64_t> uinlst;
- std::vector<test_node> nodelst;
-
- MSGPACK_DEFINE(num, str, uinlst, nodelst);
- };
每個nodelst中插入16個node,每個node中的idlst插入16個id,同1中的測試方法,得到測試結果如下:
總耗時(s) |
循環次數 |
平均每次耗時(ms) |
0.025401 |
100 |
0.25401 |
0.248396 |
1000 |
0.248396 |
2.533385 |
10000 |
0.253339 |
25.823562 |
100000 |
0.258236 |
基本上每次打包解包一次要耗時0.25ms,每秒估算可以做4k次打包解包,速度還是不錯的。
3. 加上crc校驗
如果每個循環中,打包過程加上crc的計算,解包過程中加上crc校驗,得到測試結果如下:
總耗時(s) |
循環次數 |
平均每次耗時(ms) |
0.025900 |
100 |
0.25900 |
0.260424 |
1000 |
0.260424 |
2.649585 |
10000 |
0.264959 |
26.855452 |
100000 |
0.268555 |
基本上每次打包解包耗時0.26ms左右,與沒有crc差別不大;