• vector 测试


    vector 测试

    写个简单的东西来测试一下数据很多时候几种创建 vector 的方法,结果有点意思:

    #include <iostream>
    #include <sys/time.h>
    #include <vector>
    using namespace std;
    typedef unsigned int   uint32;
    
    struct Obj
    {
        Obj(int a1, int b1, int c1) : a(a1), b(b1), c(c1) {}
        Obj(){};
        int a;
        int b;
        int c;
    };
    
    static inline uint32 get_timems()
    {
        struct timeval tv;
        return gettimeofday(&tv, NULL) == 0 ? 
                (tv.tv_sec * 1000 + tv.tv_usec / 1000):0;
    }
    
    #define N       10000000
    #define LOG(X)  printf(X ", costs: %u msecs
    ", get_timems() - ts);
    #define ITS()       ts=get_timems()
    
    
    int main(int argc, char *argv[])
    {
        uint32 ts = get_timems();
        vector<Obj> v;
        for (int i = 0; i < N; ++i)
        {
            v.push_back(Obj(i, i-1, i-2));
        }
    
        LOG("Create and push_back");
    
        ITS();
        vector<Obj> v4;
        vector<Obj>::const_iterator iter = v.begin();
        vector<Obj>::const_iterator end  = v.end();
        for (; iter != end; ++iter)
        {
            Obj o(iter->a, iter->b * 2, iter->c * 3);
            v4.push_back(o);
        }
        LOG("Create and modify and push_back");
    
        ITS();
        vector<Obj> v5;
        v5.resize(N);
        for (int i = 0; i < N; ++i)
        {
            v5[i].a = v[i].a;
            v5[i].b = v[i].b*2;
            v5[i].c = v[i].c*3;
        }
        LOG("Resize and modify");
    
    
        ITS();
        vector<Obj> v6;
        v5.reserve(N);
        for (int i = 0; i < N; ++i)
        {
            v6.push_back(Obj (iter->a, iter->b * 2, iter->c * 3));
        }
        LOG("Reserver and push_back");
    
        return 0;
    }
    

    输出如下:

    Welcome to the Emacs shell
    
    ~/tmp $ ~/tmp $ ./test
    Create and push_back, costs: 1057 msecs
    Create and modify and push_back, costs: 1244 msecs
    Resize and modify, costs: 447 msecs
    Reserver and push_back, costs: 1181 msecs
    
  • 相关阅读:
    JAVA的向上转型 和 向下转型
    Mobx 常用函数整理
    HTTP错误代码对应
    D3官网上的力导图
    用D3画简单的力导图
    nodejs 爬图片
    nodejs 爬热搜
    canvas 图片旋转 导出下载
    canvas 电子签名
    canvas 音乐跳动效果
  • 原文地址:https://www.cnblogs.com/yangyingchao/p/3473774.html
Copyright © 2020-2023  润新知