Created
November 25, 2022 01:55
-
-
Save ttsugriy/0fd6cc2a3693436411922125921c462c to your computer and use it in GitHub Desktop.
std::function vs y combinator 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 <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