Skip to content

Instantly share code, notes, and snippets.

@ttsugriy
Created November 25, 2022 01:55
Show Gist options
  • Save ttsugriy/0fd6cc2a3693436411922125921c462c to your computer and use it in GitHub Desktop.
Save ttsugriy/0fd6cc2a3693436411922125921c462c to your computer and use it in GitHub Desktop.
std::function vs y combinator benchmark
#include <functional>
int fact_std_func(int n) {
std::function<int(int)> fact = [&](auto n) {
if (n == 1) return 1;
return n * fact(n-1);
};
return fact(n);
}
int fact_comb(int n) {
auto fact = [](auto n, auto self) -> int {
if (n == 1) return 1;
return n * self(n-1, self);
};
return fact(n, fact);
}
const int n = 1000;
static void FactStdFunc(benchmark::State& state) {
for (auto _ : state) {
benchmark::DoNotOptimize(fact_std_func(n));
}
}
BENCHMARK(FactStdFunc);
static void FactComb(benchmark::State& state) {
for (auto _ : state) {
benchmark::DoNotOptimize(fact_comb(n));
}
}
BENCHMARK(FactComb);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment