Created
November 16, 2018 18:50
-
-
Save asumagic/4d24a7500e6b1036f619bc4895d10757 to your computer and use it in GitHub Desktop.
generator iterator benchmark test
This file contains hidden or 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 <algorithm> | |
#include <iterator> | |
#include <vector> | |
// Generator Iterator test | |
namespace impl | |
{ | |
template<class Func> | |
class generator_iterator : public std::iterator< | |
std::random_access_iterator_tag, | |
int, | |
long, | |
const int*, | |
int | |
> | |
{ | |
const Func& _func = {}; | |
long _count; | |
public: | |
generator_iterator(Func& func, long count) : | |
_func{func}, | |
_count{count} | |
{} | |
auto operator++() { | |
--_count; | |
return *this; | |
} | |
auto operator-(generator_iterator<Func> other) const { | |
return other._count - _count; | |
} | |
auto operator*() const { | |
return _func(); | |
} | |
bool operator!=(generator_iterator<Func> other) const { | |
return _count != other._count; | |
} | |
}; | |
} | |
template<class Func> | |
impl::generator_iterator<Func> genit(Func& func, long count = 0) | |
{ | |
return {func, count}; | |
} | |
// Main test | |
void benchmark_classic(benchmark::State& state) | |
{ | |
for (auto _ : state) { | |
std::vector<int> ret(15); | |
std::generate(ret.begin(), ret.end(), rand); | |
benchmark::DoNotOptimize(ret); | |
} | |
} | |
BENCHMARK(benchmark_classic); | |
void benchmark_genit(benchmark::State& state) | |
{ | |
for (auto _ : state) { | |
std::vector<int> ret(genit(rand, 15), genit(rand)); | |
benchmark::DoNotOptimize(ret); | |
} | |
} | |
BENCHMARK(benchmark_genit); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment