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