psemek/libs/util/tests/hash_table.cpp

184 lines
3.2 KiB
C++

#include <psemek/test/test.hpp>
#include <psemek/util/hash_table.hpp>
#include <psemek/random/generator.hpp>
#include <algorithm>
#include <unordered_set>
#include <unordered_map>
using namespace psemek;
using namespace psemek::util;
test_case(util_hash__set_benchmark)
{
random::generator rng;
std::vector<int> values;
int const count = 1024 * 1024;
for (int i = 0; i < count; ++i)
values.push_back(i);
std::shuffle(values.begin(), values.end(), rng);
test_profile(hash_set_total)
{
hash_set<int> set;
test_profile(hash_set_insert)
{
for (auto value : values)
set.insert(value);
expect_equal(set.size(), count);
}
test_profile(hash_set_iterate)
{
int size = 0;
for (auto value : set)
{
expect(0 <= value && value < count);
++size;
}
expect_equal(size, count);
}
test_profile(hash_set_find)
{
for (auto value : values)
{
auto it = set.find(value);
expect(it != set.end());
expect_equal(*it, value);
}
}
test_profile(hash_set_clear)
{
set.clear();
}
}
test_profile(unordered_set_total)
{
std::unordered_set<int> set;
test_profile(unordered_set_insert)
{
for (auto value : values)
set.insert(value);
expect_equal(set.size(), count);
}
test_profile(unordered_set_iterate)
{
int size = 0;
for (auto value : set)
{
expect(0 <= value && value < count);
++size;
}
expect_equal(size, count);
}
test_profile(unordered_set_find)
{
for (auto value : values)
{
auto it = set.find(value);
expect(it != set.end());
expect_equal(*it, value);
}
}
test_profile(unordered_set_clear)
{
set.clear();
}
}
}
test_case(util_hash__map_benchmark)
{
random::generator rng;
std::vector<int> keys;
int const count = 1024 * 1024;
for (int i = 0; i < count; ++i)
keys.push_back(i);
std::shuffle(keys.begin(), keys.end(), rng);
test_profile(hash_map_total)
{
hash_map<int, int> map;
test_profile(hash_map_insert)
{
for (auto key : keys)
map.insert({key, -key});
expect_equal(map.size(), count);
}
test_profile(hash_map_iterate)
{
int size = 0;
for (auto const & pair : map)
{
expect(0 <= pair.first && pair.first < count);
expect_equal(pair.second, -pair.first);
++size;
}
expect_equal(size, count);
}
test_profile(hash_map_find)
{
for (auto key : keys)
{
auto it = map.find(key);
expect(map.find(key) != map.end());
expect_equal(it->second, -key);
}
}
test_profile(hash_map_clear)
{
map.clear();
}
}
test_profile(unordered_map_total)
{
std::unordered_map<int, int> map;
test_profile(unordered_map_insert)
{
for (auto key : keys)
map.insert({key, -key});
}
test_profile(unordered_map_iterate)
{
int size = 0;
for (auto const & pair : map)
{
expect(0 <= pair.first && pair.first < count);
expect_equal(pair.second, -pair.first);
++size;
}
expect_equal(size, count);
}
test_profile(unordered_map_find)
{
for (auto key : keys)
{
auto it = map.find(key);
expect(map.find(key) != map.end());
expect_equal(it->second, -key);
}
}
test_profile(unordered_map_clear)
{
map.clear();
}
}
}