Created
November 17, 2024 19:31
-
-
Save SollyBunny/110348dd524c1d36ceacf48367be8916 to your computer and use it in GitHub Desktop.
Benchmark containers
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
#include <cstdint> | |
#include <map> | |
#include <unordered_map> | |
#include <iostream> | |
#include <chrono> | |
#include <functional> | |
#include <cstdlib> | |
#include <cstring> | |
volatile int out; | |
static inline uint64_t randl(void) { | |
return ((uint64_t)std::rand() << 32) | std::rand(); | |
} | |
static void Map() { | |
std::map<uint64_t, int> map; | |
for (int i = 0; i < 1000; ++i) { | |
map[randl()] = std::rand(); | |
} | |
for (int i = 0; i < 1000; ++i) { | |
uint64_t key = randl(); | |
if (auto it = map.find(key); it != map.end()) | |
out = it->second; | |
} | |
} | |
static void UnorderedMap() { | |
std::unordered_map<uint64_t, int> map; | |
for (int i = 0; i < 1000; ++i) { | |
map[randl()] = std::rand(); | |
} | |
for (int i = 0; i < 1000; ++i) { | |
uint64_t key = randl(); | |
if (auto it = map.find(key); it != map.end()) | |
out = it->second; | |
} | |
} | |
static void Array() { | |
size_t size = 4096; // double what ddnet has now | |
int Array[size]; | |
memset(Array, 0, sizeof(Array)); | |
for (int i = 0; i < 1000; ++i) { | |
Array[randl() % size] = std::rand(); | |
} | |
for (int i = 0; i < 1000; ++i) { | |
uint64_t key = randl() % size; | |
if (Array[key]) | |
out = Array[key]; | |
} | |
} | |
static void Benchmark(const std::function<void()>& func, const std::string& func_name) { | |
using namespace std::chrono; | |
constexpr int iterations = 10; | |
double total_time = 0.0; | |
for (int i = 0; i < iterations; ++i) { | |
auto start = high_resolution_clock::now(); | |
func(); | |
auto end = high_resolution_clock::now(); | |
duration<double> elapsed = end - start; | |
total_time += elapsed.count(); | |
} | |
float seconds = total_time / iterations; | |
float ms = seconds * 1e6; | |
std::cout << "Average time for " << func_name << ": " | |
<< ms << "microseconds\n"; | |
} | |
int main(void) { | |
// Seed the random number generator | |
std::srand(static_cast<unsigned>(std::time(nullptr))); | |
// Benchmark the Map function | |
Benchmark(Map, "Map"); | |
Benchmark(UnorderedMap, "Unorded Map"); | |
Benchmark(Array, "Array"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment