• Boost文本序列化和二进制序列化的效率比较


    文本序列化需要对二进制数据进行转换,还要加入分隔符,因此不仅效率低而且耗费更多的空间。写了一个小程序比较一下二者效率相差相差多少,发现还是蛮悬殊的。例子程序中对同一个对象序列化100万次,该对象包含几种常用的数据类型,除了比较速度,还比较二者耗费的空间大小。程序代码如下:
    #include <iostream>
    #include <string>
    #include <sstream>

    #include <boost/archive/text_oarchive.hpp>
    #include <boost/archive/text_iarchive.hpp>

    #include <boost/archive/binary_iarchive.hpp>
    #include <boost/archive/binary_oarchive.hpp>

    using namespace std;

    class Test
    {
    public:

    friend class boost::serialization::access;

    Test(bool b, char ch, int i, double d, string str)
    : m_bool(b), m_char(ch), m_int(i), m_double(d), m_str(str)
    {
    }

        template<class Archive>
        void serialize(Archive & ar, const unsigned int version)
        {
    ar& m_bool;
    ar& m_char;
    ar& m_int;
    ar& m_double;
    ar& m_str;
        }

    private:
    bool m_bool;
    char m_char;
    int m_int;
    double m_double;
    string m_str;
    };

    int main()
    {
    Test test(true, 'm', 50, 17.89, "fuzhijie");

    stringstream binary_sstream;
    stringstream text_sstream;

    long long begin, end;

    int size;

    //使用二进制的方式序列化
    boost::archive::text_oarchive text_oa(text_sstream);
    boost::archive::binary_oarchive binary_oa(binary_sstream);

    begin = time(NULL);
    for(int i = 0; i < 1000000; ++i)
    {
    text_oa << test;
    }
    end = time(NULL);

    size = text_sstream.tellp() / (1024 * 1024);

    cout << "text serialization seconds: " << end - begin << ", space: " << size << endl;

    begin = time(NULL);
    for(int i = 0; i < 1000000; ++i)
    {
    binary_oa << test;
    }
    end = time(NULL);

            //以MB为单位
    size = binary_sstream.tellp() / (1024 * 1024);

    cout << "binary serialization seconds: " << end - begin << ", space: " << size << endl;

    return 0;
    };
            连续测试三次,结果如下:
    text serialization seconds: 37, space: 37
    binary serialization seconds: 8, space: 24

    text serialization seconds: 40, space: 37
    binary serialization seconds: 8, space: 24

    text serialization seconds: 37, space: 37
    binary serialization seconds: 8, space: 24
           从结果可以看出,二者速度相差5倍左右,耗费空间大小相差1.5倍左右。
  • 相关阅读:
    redis 定义序列号
    mac下搭建phalcon扩展以及phalcon-devtools扩展
    rabbitmq集群架构(转载)
    mysql下limit分页优化思路
    ffmpeg图片格式转换,webp转换成jpg,webp转换成png,jpg转换成png,jpg转换成webp,png转换成webp,png转换成jpg
    sed替换多个字符串在一条命令里面
    CentOS7减轻DDOS攻击,使用fail2ban预防CC攻击
    ffmpeg改变jpg,png,webp图片大小
    wget下载github的releases的软件
    CentOS6.5设置IPTables防火墙
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13318632.html
Copyright © 2020-2023  润新知