Skip to content

Instantly share code, notes, and snippets.

@kristerw
Last active July 20, 2017 09:37
Show Gist options
  • Save kristerw/2802a38d54a29ffa781c64e1c50f63df to your computer and use it in GitHub Desktop.
Save kristerw/2802a38d54a29ffa781c64e1c50f63df to your computer and use it in GitHub Desktop.
#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