测试代码
#include "stdafx.h"
#include
#include
#include
#include
#include
#include
#include
#include
#pragma comment(lib,"psapi.lib")
#define DATA_SIZE 100000
#define SEARCH_DATA 1000000
void showMemoryInfo(void)
{
HANDLE handle = GetCurrentProcess();
PROCESS_MEMORY_COUNTERS pmc;
GetProcessMemoryInfo(handle, &pmc, sizeof(pmc));
std::cout << "内存使用:" << pmc.WorkingSetSize / 1000 << "K/" << pmc.PeakWorkingSetSize / 1000 << "K + " <<
pmc.PagefileUsage / 1000 << "K/" << pmc.PeakPagefileUsage / 1000 << "K" << std::endl;
}
void main(){
std::ofstream ofs("d:\\test_map.txt");
std::cout.set_rdbuf(ofs.rdbuf());
std::vector datas(DATA_SIZE);
std::vector searchs(SEARCH_DATA);
for (int i = 0; i < DATA_SIZE; i++)
{
int random = rand();
datas[i] = random;
//std::cout << random << " ";
}
std::cout << std::endl << std::endl;
for (int i = 0; i < SEARCH_DATA; i++)
{
int random = rand();
searchs[i] = random;
//std::cout << random << " ";
}
showMemoryInfo();
std::cout << std::endl << std::endl;
//seach --set
TimeSpan span;
span.start();
std::multiset sets;
for each (auto one in datas)
{
sets.insert(one);
}
std::cout << "set build use time : " << span.elapsed() << std::endl;
span.restart();
for each (auto one in searchs)
{
sets.find(one);
}
std::cout << "set use time : " << span.elapsed() << std::endl;
showMemoryInfo();
std::cout << std::endl << std::endl;
//search - hashset
span.restart();
std::hash_multiset hsets;
for each (auto one in datas)
{
hsets.insert(one);
}
std::cout << "hashset use time : " << span.elapsed() << std::endl;
span.restart();
for each (auto one in searchs)
{
hsets.find(one);
}
std::cout << "hashset use time : " << span.elapsed() << std::endl;
showMemoryInfo();
std::cout << std::endl << std::endl;
//normal search
span.restart();
for each (auto one in searchs)
{
std::find(datas.begin(), datas.end(), one);
}
std::cout << "normal use time : " << span.elapsed() << std::endl;
showMemoryInfo();
// redirect cout to /dev/null
ofs.close();
}
测试结果
内存使用:6905K/6905K + 5050K/5050K
set build use time : 51
set use time : 382
内存使用:10149K/10149K + 8269K/8269K
hashset use time : 24
hashset use time : 52
内存使用:13643K/13643K + 11771K/11771K
normal use time : 9810
内存使用:13643K/13643K + 11771K/11771K
可以看出
1. 数据随机性比较大的情况下,hashmap的性能是最好的, 建表时间也优于map。
2. 内存使用hashmap和map差不多。