From fcb214064030d81279bd1b7f756c3f2216045afb Mon Sep 17 00:00:00 2001 From: Emiel Por Date: Mon, 16 Dec 2024 17:02:30 -0800 Subject: [PATCH] Add UUID generator based on two MT19937 pseudo-random number generators seeded by true randomness. --- benchmarks/uuid_generator.cpp | 32 ++++++++++++++++++++++++++++++++ catkit_core/CMakeLists.txt | 1 + catkit_core/UuidGenerator.cpp | 21 +++++++++++++++++++++ catkit_core/UuidGenerator.h | 17 +++++++++++++++++ 4 files changed, 71 insertions(+) create mode 100644 benchmarks/uuid_generator.cpp create mode 100644 catkit_core/UuidGenerator.cpp create mode 100644 catkit_core/UuidGenerator.h diff --git a/benchmarks/uuid_generator.cpp b/benchmarks/uuid_generator.cpp new file mode 100644 index 00000000..bb2879cf --- /dev/null +++ b/benchmarks/uuid_generator.cpp @@ -0,0 +1,32 @@ +#include "UuidGenerator.h" +#include "Timing.h" + +#include + +int main() +{ + const size_t N = 100000000; + + UuidGenerator generator; + + char uuid[16]; + + std::cout << std::hex; + + auto start = GetTimeStamp(); + + for (size_t i = 0; i < N; ++i) + { + generator.GenerateUuid(uuid); + } + + auto end = GetTimeStamp(); + + std::cout << std::dec; + + std::cout << "Time: " << (end - start) / 1e9 << " sec" << std::endl; + std::cout << "Throughput: " << N / ((end - start) / 1e9) << " ops/s" << std::endl; + std::cout << "Time per operation: " << (end - start) / N << " ns" << std::endl; + + return 0; +} diff --git a/catkit_core/CMakeLists.txt b/catkit_core/CMakeLists.txt index 6258d432..360db308 100644 --- a/catkit_core/CMakeLists.txt +++ b/catkit_core/CMakeLists.txt @@ -35,6 +35,7 @@ add_library(catkit_core STATIC Util.cpp PoolAllocator.cpp FreeListAllocator.cpp + UuidGenerator.cpp proto/core.pb.cc proto/logging.pb.cc proto/testbed.pb.cc diff --git a/catkit_core/UuidGenerator.cpp b/catkit_core/UuidGenerator.cpp new file mode 100644 index 00000000..ea68bcaf --- /dev/null +++ b/catkit_core/UuidGenerator.cpp @@ -0,0 +1,21 @@ +#include "UuidGenerator.h" + +UuidGenerator::UuidGenerator() +{ + std::random_device random_device; + + for (size_t i = 0; i < 2; ++i) + { + std::seed_seq seed{random_device(), random_device()}; + m_Engines[i].seed(seed); + } +} + +void UuidGenerator::GenerateUuid(char *uuid) +{ + for (size_t i = 0; i < 2; ++i) + { + std::uint64_t value = m_Engines[i](); + *reinterpret_cast(uuid + i * 8) = value; + } +} diff --git a/catkit_core/UuidGenerator.h b/catkit_core/UuidGenerator.h new file mode 100644 index 00000000..244b828d --- /dev/null +++ b/catkit_core/UuidGenerator.h @@ -0,0 +1,17 @@ +#ifndef UUID_GENERATOR_H +#define UUID_GENERATOR_H + +#include + +class UuidGenerator +{ +public: + UuidGenerator(); + + void GenerateUuid(char *uuid); + +private: + std::mt19937_64 m_Engines[2]; +}; + +#endif // UUID_GENERATOR_H