Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
#include <vector>
long run_forloop(std::vector<int> const &vec, long to_find)
{
long len = vec.end() - vec.begin();
const int *p = &vec[0];
long i, acc = 0;
for (i = 0; i < len; i++) {
acc += p[i];
if (to_find < acc)
break;
}
return i;
}
#include <vector>
#include <benchmark/benchmark.h>
long run_std(std::vector<int> const &lengths, long to_find);
long run_range(std::vector<int> const &lengths, long to_find);
long run_forloop(std::vector<int> const &lengths, long to_find);
static void BM_std(benchmark::State &state)
{
const int len = state.range(0);
std::vector<int> const vec(len, 1);
const long to_find = len - 10;
while (state.KeepRunning())
{
run_std(vec, to_find);
}
}
static void BM_range(benchmark::State &state)
{
const int len = state.range(0);
std::vector<int> const vec(len, 1);
const long to_find = len - 10;
while (state.KeepRunning())
{
run_range(vec, to_find);
}
}
static void BM_forloop(benchmark::State &state)
{
const int len = state.range(0);
std::vector<int> const vec(len, 1);
const long to_find = len - 10;
while (state.KeepRunning())
{
run_forloop(vec, to_find);
}
}
BENCHMARK(BM_std)->Arg(1 << 10);
BENCHMARK(BM_range)->Arg(1 << 10);
BENCHMARK(BM_forloop)->Arg(1 << 10);
BENCHMARK_MAIN();
#include <vector>
#include <range/v3/all.hpp>
long run_range(std::vector<int> const &lengths, long to_find)
{
auto const found_index = ranges::distance(lengths
| ranges::view::transform(ranges::convert_to<long>{})
| ranges::view::partial_sum()
| ranges::view::take_while([=](auto const i) {
return !(to_find < i);
}));
return found_index;
}
#include <vector>
#include <algorithm>
long run_std(std::vector<int> const &lengths, long to_find)
{
auto accumulated_length = 0l;
auto found = std::find_if(lengths.begin(), lengths.end(),
[&](auto const &val) {
accumulated_length += val;
return to_find < accumulated_length;
});
auto const found_index = std::distance(lengths.begin(), found);
return found_index;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment