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\n", 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
posted @ 2013-12-13 20:24  英超  Views(429)  Comments(0Edit  收藏  举报