测试std::unordered_map的hash冲突

12 篇文章 0 订阅

std::unordered_map的实现为hash表,所以hash值范围越小,越容易出现冲突,效率越低

m用的是自定义的hash函数hash值只有0和1,m2用默认hash函数

struct myhash{
    size_t constexpr operator() (int a) const {
        return a % 2;
    }
};

int main()
{
    timeval t1, t2;
    size_t n = 10000;
    size_t times = 10;

    for (size_t time = 0; time < times; ++time) {

        std::unordered_map<int, int, myhash> m;

        gettimeofday(&t1, nullptr);
        for (size_t i = 0; i < n; ++i) {
            m.emplace(i, i);
        }
        gettimeofday(&t2, nullptr);
        printf("%lf\n", (t2.tv_sec - t1.tv_sec) * 1000 + (t2.tv_usec - t1.tv_usec) / 1000.0);

        gettimeofday(&t1, nullptr);
        m.find(n / 2);
        gettimeofday(&t2, nullptr);
        printf("%lf\n", (t2.tv_sec - t1.tv_sec) * 1000 + (t2.tv_usec - t1.tv_usec) / 1000.0);

        std::unordered_map<int, int> m2;

        gettimeofday(&t1, nullptr);
        for (size_t i = 0; i < n; ++i) {
            m2.emplace(i, i);
        }
        gettimeofday(&t2, nullptr);
        printf("%lf\n", (t2.tv_sec - t1.tv_sec) * 1000 + (t2.tv_usec - t1.tv_usec) / 1000.0);

        gettimeofday(&t1, nullptr);
        m2.find(n / 2);
        gettimeofday(&t2, nullptr);
        printf("%lf\n\n", (t2.tv_sec - t1.tv_sec) * 1000 + (t2.tv_usec - t1.tv_usec) / 1000.0);

    }
}

n为数据量,times为测试次数,下面结果取最后一次测试结果

n为100,1000,10000时

时间(ms):

m 插入      0.104000    9.433000    913.546000

m 查找      0.004000    0.018000    0.146000

m2 插入    0.028000    9.433000    2.230000

m2 查找    0.004000    0.004000    0.004000

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值