Skip to content

Instantly share code, notes, and snippets.

@blackjack
Created March 23, 2021 14:30
Show Gist options
  • Save blackjack/f788eb7588b2b8270f2f85b5f3bf9b20 to your computer and use it in GitHub Desktop.
Save blackjack/f788eb7588b2b8270f2f85b5f3bf9b20 to your computer and use it in GitHub Desktop.
Div vs And
#include <random>
#include <vector>
std::vector<int> generateRandomVector(int size)
{
std::vector<int> vec(size);
std::generate(begin(vec), end(vec), rand);
return vec;
}
static void DivByConstant(benchmark::State& state) {
int value = 1301081;
int divisor = 1024;
for (auto _ : state) {
int remainder = value % divisor;
benchmark::DoNotOptimize(remainder);
}
}
BENCHMARK(DivByConstant);
static void DivByUnsignedConstant(benchmark::State& state) {
int value = 1301081;
unsigned int divisor = 1024;
for (auto _ : state) {
int remainder = value % divisor;
benchmark::DoNotOptimize(remainder);
}
}
BENCHMARK(DivByUnsignedConstant);
static void BitwiseAnd(benchmark::State& state) {
int value = 1301081;
unsigned int divisor = 0x3FF;
for (auto _ : state) {
int remainder = value & divisor;
benchmark::DoNotOptimize(remainder);
}
}
BENCHMARK(BitwiseAnd);
static const auto values = generateRandomVector(1'000'000);
static const auto divisors = generateRandomVector(1'000'000);
static void BitwiseAndRandom(benchmark::State& state) {
int divisor = 0x3FF;
for (auto _ : state) {
auto value = values[state.iterations()];
int remainder = value & divisor;
benchmark::DoNotOptimize(remainder);
}
}
BENCHMARK(BitwiseAndRandom);
static void DivByConstantRandom(benchmark::State& state) {
int divisor = 1024;
for (auto _ : state) {
auto value = values[state.iterations()];
int remainder = value % divisor;
benchmark::DoNotOptimize(remainder);
}
}
BENCHMARK(DivByConstantRandom);
static void BitwiseAndRandomDivisor(benchmark::State& state) {
for (auto _ : state) {
auto value = values[state.iterations()];
auto divisor = divisors[state.iterations()];
int remainder = value & divisor;
benchmark::DoNotOptimize(remainder);
}
}
BENCHMARK(BitwiseAndRandomDivisor);
static void DivByConstantRandomDivisor(benchmark::State& state) {
for (auto _ : state) {
auto value = values[state.iterations()];
auto divisor = divisors[state.iterations()];
int remainder = value % divisor;
benchmark::DoNotOptimize(remainder);
}
}
BENCHMARK(DivByConstantRandomDivisor);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment