linux下unordered_map和map在小数据下性能差异

来源:互联网 发布:cf英雄武器抽奖 软件 编辑:程序博客网 时间:2024/06/05 06:49

说起性能,没有测试,还是没有发言权:

#include <map>#include <boost/unordered_map.hpp>#include <string>#include <iostream>#include <sys/time.h>#include <stdio.h>#include <stdlib.h>#include <hash_map>#include <unordered_map>timeval g_ts;long getnow(){    gettimeofday(&g_ts, NULL);    return g_ts.tv_usec;}int size = 10;int getrand(){    return rand()%size;}int main(int agr, char** argc){    if (agr < 2){        printf("uage gar < 2\n");        exit(1);    }    size = atoi(argc[1]);    std::unordered_map<int, std::string> map1;    long t1 = getnow();    for (int i = 0; i < size; ++i){        map1.insert(std::make_pair(getrand(),"tes"));    }    for(int i = 0; i < size; ++i){        map1.find(getrand());    }        int rand1 = getrand();    for (int i = 0; i < size; ++i){        map1.erase(getrand());    }    printf("unordered_map %d insert time:%ld\n", size, getnow()-t1);     std::map<int, std::string> map2;    t1 = getnow();    for(int i = 0; i < size; ++i){        map2.insert(std::make_pair(getrand(), "tes"));    }    for(int i = 0; i < size; ++i){        map2.find(getrand());    }    for(int i = 0; i < size; ++i){        map2.erase(getrand());    }    printf("std::map insert&find %d times use:%ld\n", size, getnow() - t1);}




输出结果为:

allen@allenPC:~/code/c++code$ ./tetsb 10
unordered_map 10 insert time:44
std::map insert&find 10 times use:33
allen@allenPC:~/code/c++code$ ./tetsb 100
unordered_map 100 insert time:186
std::map insert&find 100 times use:212
allen@allenPC:~/code/c++code$ ./tetsb 200
unordered_map 200 insert time:330
std::map insert&find 200 times use:453
allen@allenPC:~/code/c++code$ ./tetsb 500
unordered_map 500 insert time:792
std::map insert&find 500 times use:1236
allen@allenPC:~/code/c++code$ ./tetsb 1000
unordered_map 1000 insert time:1552
std::map insert&find 1000 times use:2587
allen@allenPC:~/code/c++code$ 



看来还是如果数据量较小,unorderedmap更快!

0 0
原创粉丝点击