Last active
August 11, 2023 22:09
-
-
Save fabiogaluppo/7d337826644e5cf3e0a87c7fd045827d to your computer and use it in GitHub Desktop.
FNV-64 fnv1 hash Quick C++ Benchmarks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Quick C++ Benchmarks link: https://quick-bench.com/q/mvKK4FzyZGTNSFr5Qe6i1akzzro | |
#include <cstddef> | |
#include <unordered_map> | |
#include <string> | |
#include <utility> | |
static const std::uint64_t FNV1_64_INIT = 0xcbf29ce484222325ULL; | |
//FNV-1 hash | |
static std::uint64_t fnv1_hash(void* buf, std::size_t size, std::uint64_t hashval = FNV1_64_INIT) | |
{ | |
unsigned char* first = reinterpret_cast<unsigned char*>(buf); | |
unsigned char* last = first + size; | |
while (first < last) | |
{ | |
hashval += (hashval << 1) + (hashval << 4) + (hashval << 5) + (hashval << 7) + (hashval << 8) + (hashval << 40); | |
hashval ^= static_cast<std::uint64_t>(*first++); | |
} | |
return hashval; | |
} | |
//FNV-1 hash | |
static inline std::uint64_t fnv1_hash(const char* buf, std::size_t size, std::uint64_t hashval = FNV1_64_INIT) | |
{ | |
return fnv1_hash(reinterpret_cast<void*>(const_cast<char*>(buf)), size, hashval); | |
} | |
//FNV-1 hash | |
static inline std::uint64_t fnv1_hash(const std::string& s, std::uint64_t hashval = FNV1_64_INIT) | |
{ | |
return fnv1_hash(s.c_str(), s.size(), hashval); | |
} | |
struct custom_key final | |
{ | |
std::string key; | |
bool operator==(const custom_key& that) const { return &that == this || that.key == this->key; } | |
}; | |
template<> | |
struct std::hash<custom_key> | |
{ | |
std::size_t operator()(const custom_key& ck) const noexcept | |
{ | |
return fnv1_hash(ck.key); | |
} | |
}; | |
static void BM_HashtableCreationAndUpdateFNV(benchmark::State& state) { | |
std::unordered_map<custom_key, std::size_t> hashtable; | |
std::size_t i = 0; | |
for (auto _ : state) { | |
++i; | |
hashtable.emplace(custom_key{ "_" + std::to_string(i) }, i); | |
} | |
i = 0; | |
for (auto _ : state) { | |
++i; | |
hashtable[custom_key{ "_" + std::to_string(i) }] = i * i; | |
} | |
} | |
BENCHMARK(BM_HashtableCreationAndUpdateFNV); | |
static void BM_HashtableCreationAndUpdate(benchmark::State& state) { | |
std::unordered_map<std::string, std::size_t> hashtable; | |
std::size_t i = 0; | |
for (auto _ : state) { | |
++i; | |
hashtable.emplace("_" + std::to_string(i), i); | |
} | |
i = 0; | |
for (auto _ : state) { | |
++i; | |
hashtable["_" + std::to_string(i)] = i * i; | |
} | |
} | |
BENCHMARK(BM_HashtableCreationAndUpdate); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment