Last active
December 10, 2018 17:28
-
-
Save iglesias/38017a54dffc4d14e3f59c6c318af18b to your computer and use it in GitHub Desktop.
Fiddling with modern C++ enums benchmark
This file contains 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 <limits> | |
#include <unordered_map> | |
enum class binary_enum : bool { first = 0, second = 1, }; | |
constexpr size_t FIRST = static_cast<size_t>(binary_enum::first); | |
constexpr size_t SECOND = static_cast<size_t>(binary_enum::second); | |
constexpr size_t N = 1e4; | |
static void with_array(benchmark::State& state) { | |
// Code before the loop is not measured | |
std::array<std::vector<int>, 2> arr; | |
arr[FIRST] = std::vector<int>(N, 0); | |
arr[SECOND] = std::vector<int>(N, std::numeric_limits<int>::max()); | |
// Code inside this loop is measured repeatedly | |
for (auto _ : state) { | |
for (size_t i = 0; i < N; i++) { | |
arr[FIRST][i] = std::rand(); | |
arr[SECOND][i] = std::rand(); | |
} | |
// Make sure the variable is not optimized away by compiler | |
benchmark::DoNotOptimize(arr); | |
} | |
} | |
// Register the function as a benchmark | |
BENCHMARK(with_array); | |
static void with_unordered_map(benchmark::State& state) { | |
// Code before the loop is not measured | |
std::unordered_map<binary_enum, std::vector<int>> ht; | |
ht.emplace(binary_enum::first, std::vector<int>(N, 0)); | |
ht.emplace(binary_enum::second, std::vector<int>(N, std::numeric_limits<int>::max())); | |
// Code inside this loop is measured repeatedly | |
for (auto _ : state) { | |
for (size_t i = 0; i < N; i++) { | |
ht[binary_enum::first][i] = std::rand(); | |
ht[binary_enum::second][i] = std::rand(); | |
} | |
// Make sure the variable is not optimized away by compiler | |
benchmark::DoNotOptimize(ht); | |
} | |
} | |
BENCHMARK(with_unordered_map); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment