当有一个100万的kv数据,并且k是小于100万的数字,是该采用unordered_map还是数组来存储呢;结论是采用数组来访问,数组性能比unordered_map快35倍
#include <unordered_map>
#include <sys/time.h>
#include <iostream>
using namespace std;
int main() {
std::unordered_map<int, int> map;
int* a = new int[1000];
int* b = new int[1000];
for (int i=0; i< 1000; ++i) {
map[i] = i;
a[i] = i;
b[i] = (i*11 + i*i)%1000;
}
int sum = 0;
struct timeval t1,t2;
double timeuse;
gettimeofday(&t1,NULL);
for (int i = 0; i < 10000; ++i)
for (int j = 0; j < 1000; ++j) {
sum += map[j];
}
gettimeofday(&t2,NULL);
timeuse = (t2.tv_sec - t1.tv_sec) + (double)(t2.tv_usec - t1.tv_usec)/1000000.0;
cout<<"time = "<<timeuse<<endl;
sum = 0;
gettimeofday(&t1,NULL);
for (int i = 0; i < 10000; ++i)
for (int j = 0; j < 1000; ++j) {
sum += a[j];
}
gettimeofday(&t2,NULL);
timeuse = (t2.tv_sec - t1.tv_sec) + (double)(t2.tv_usec - t1.tv_usec)/1000000.0;
cout<<"time = "<<timeuse << " " << map.size() <<endl;
return 0;
}
输出
time = 0.758736 // unordered_map
time = 0.026855 // 数组