首页 > 编程语言 > 详细

python序列化模块的速度比较

时间:2019-04-01 18:22:02      阅读:157      评论:0      收藏:0      [点我收藏+]
# -*- coding: utf-8 -*-
# @Time : 2019-04-01 17:41
# @Author : cxa
# @File : dictest.py
# @Software: PyCharm
import time
import pickle
import marshal
import ujson
import msgpack


def test(data, method):
    if method == 'pickle':
        dumps = pickle.dumps
        loads = pickle.loads
    elif method == 'marshal':
        dumps = marshal.dumps
        loads = marshal.loads
    elif method == 'ujson':
        dumps = ujson.dumps
        loads = ujson.loads
    elif method == "msgpack":
        dumps = msgpack.dumps
        loads = msgpack.loads

    b = time.time()
    s = ''
    loop = 10000
    for i in range(loop):
        s = dumps(data)
    print('{} dumps time cost: {}'.format(method, time.time() - b))

    b = time.time()
    for i in range(loop):
        loads(s)
    print('{} loads time cost: {}'.format(method, time.time() - b))


def main():
    # generate test data
    data = {}
    count = 80
    for i in range(10000):
        k = '%05d' % (i % count)
        if k in data:
            data[k].append(i / count)
        else:
            data[k] = [i / count]

    print('data:', len(data))
    # test
    test(data, 'pickle')
    test(data, 'marshal')
    test(data, 'ujson')
    test(data, 'msgpack')


if __name__ == '__main__':
    main()

结果

pickle dumps time cost: 2.6049489974975586
pickle loads time cost: 3.6289799213409424
marshal dumps time cost: 2.2469120025634766
marshal loads time cost: 2.907557964324951
ujson dumps time cost: 8.108527183532715
ujson loads time cost: 4.873885869979858
msgpack dumps time cost: 2.671412944793701
msgpack loads time cost: 3.2492690086364746

python序列化模块的速度比较

原文:https://www.cnblogs.com/c-x-a/p/10637870.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!