现在的位置: 首页 > 综合 > 正文

pickle 协议性能测试

2013年09月22日 ⁄ 综合 ⁄ 共 2244字 ⁄ 字号 评论关闭
先看文档:
pickle.dumps(obj[,protocol])

Return the pickled representation of the object as a string, instead of writing it to a file.

If the protocol parameter is omitted, protocol 0 is used. If protocol is specified as a negative value orHIGHEST_PROTOCOL,
the highest protocol version will be used.

Changed in version 2.3:
The protocol parameter was added.

这里使用的是cPickle做测试,首先看一下dumps() 函数的默认协议,也就是参数0运行的情况:

测试代码如下:

#! /usr/bin/env python
#coding=utf-8

import time
import cPickle as pickle

test_data = {
    'baihe': {
        'name': unicode('百合', 'utf-8'),      
        'say': unicode('清新,淡雅,花香', 'utf-8'),     
        'grow_time': 0.5,        
        'fruit_time':  0.5,     
        'super_time': 0.5,      
        'total_time': 1,    
        'buy':{'gold':2, } ,      
        'harvest_fruit': 1,    
        'harvest_super': 1,    
        'sale': 1,         
        'level_need': 0,   
        'experience' : 2,   
        'exp_fruit': 1,      
        'exp_super': 1,     
        'used': True,
    },
    '1':{
        'interval' : 0.3, 
        'probability' : {
            '98': {'chips' : (5, 25), },
            '2' : {'gem' : (1,1), },
        },
    },
    '2':{
        'unlock' : {'chips':1000, 'FC':10,},
        'interval' : 12, 
        'probability' : {
            '70': {'chips' : (120, 250), },
            '20': {'gem' : (1,1), },
            '10': {'gem' : (2,2), },
        },
    },
    'one':{
        '10,5' :{'id':'m01', 'Y':1, 'msg':u'在罐子里发现了一个银币!',},
        '3,7'  :{'id':'m02', 'Y':10,'msg':u'发现了十个银币!好大一笔钱!',},
        '15,5' :{'id':'m03', 'Y':2, 'msg':u'一只老鼠跑了过去',},
        '7,4'  :{'id':'m04', 'Y':4, 'msg':u'发现了四个生锈的银币……',},
        '2,12' :{'id':'m05', 'Y':6, 'msg':u'六个闪亮的银币!',},
    },    
    
}

start_time = time.time()
print "start_time:", start_time

j = 1
while True:
    j += 1
    # 分别使用默认--也就是协议参数为0,和可选的1,2进行测试,如pickle.dumps(test_data, 1)
    data = pickle.dumps(test_data)
    data_length = len(data)
    end_time = time.time()
    if end_time - start_time >= 1 :
        break
print "loop_num:", j
print "end_time:  ",end_time
print data_length

默认的dump()测试结果:

start_time: 1343873550.62
loop_num: 13260
end_time:   1343873551.62
1377

再把协议调整成为1,测试结果:

start_time: 1343873648.89
loop_num: 34514
end_time:   1343873649.89
868

可以看到,执行效率约为协议0的2.6倍,生成的bit数是协议0的60%。

再把协议换成协议2,测试结果:

start_time: 1343874146.49
loop_num: 35254
end_time:   1343874147.49
862

可以看到,使用协议2,无论在执行效率、压缩效率上,比起协议1来都提高不大。

总结:

    如果使用pickle的dumps函数的话,从性能和压缩比考虑,应该使用协议1或者协议2。
pickle的dumps()默认使用协议0,是为了向python2.3之前的版本兼容。如果使用协议3,数据将只能用于python3。

抱歉!评论已关闭.