Branchless conversion of a hex character to its value
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
// Requires google's benchmark library: https://github.com/google/benchmark | |
#include <benchmark/benchmark.h> | |
#include <cstdint> | |
constexpr auto k_samples_count = 1000000u; | |
uint8_t random_char() | |
{ | |
constexpr char chars[] = "0123456789abcdefABCDEF"; | |
return chars[rand() % 22u]; | |
} | |
char to_value_with_branches(uint8_t c) | |
{ | |
if (c >= 'a') { | |
c -= 'a' - ':'; | |
} else if (c >= 'A') { | |
c -= 'A' - ':'; | |
} | |
return c - '0'; | |
} | |
static void OldRustyCalculations(benchmark::State& state) | |
{ | |
srand(0); | |
while (state.KeepRunning()) { | |
for (auto i = 0u; i < k_samples_count; ++i) { | |
const auto c = to_value_with_branches(random_char()); | |
benchmark::DoNotOptimize(c); | |
} | |
} | |
} | |
BENCHMARK(OldRustyCalculations); | |
char to_value_branchless(uint8_t c) | |
{ | |
constexpr uint8_t to_add[] = { 0, 9 }; | |
const bool is_alpha_char = (c & 0b01000000u); | |
return (c & 0x0fu) + to_add[is_alpha_char]; | |
} | |
static void ShinyBranchless(benchmark::State& state) | |
{ | |
srand(0); | |
while (state.KeepRunning()) { | |
for (auto i = 0u; i < k_samples_count; ++i) { | |
const auto c = to_value_branchless(random_char()); | |
benchmark::DoNotOptimize(c); | |
} | |
} | |
} | |
BENCHMARK(ShinyBranchless); | |
BENCHMARK_MAIN(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment