Google Benchmark sorting algorithms

Viewed 299

I would like to benchmark various sorting algorithms using Google Benchmark. If I use

static void StdSort(benchmark::State& state) {
  auto v = generate_random_vector(state.range(0));
  for (auto _ : state)
    std::sort(std::begin(v), std::end(v));
}
BENCHMARK(StdSort)->Arg(10)->Arg(1000)->Arg(1'000'000);

I will end up sorting a pre-sorted vector most of the time. I read in the manual that I could use manual timing to only benchmark the sections I care about:

static void StdSort(benchmark::State& state) {
  auto v = generate_random_vector(state.range(0));
  std::default_random_engine gen;
  for (auto _ : state) {
    auto start = std::chrono::high_resolution_clock::now();
    std::sort(std::begin(v), std::end(v));
    auto end = std::chrono::high_resolution_clock::now();
    auto elapsed_seconds =
        std::chrono::duration_cast<std::chrono::duration<double>>(end - start);

    state.SetIterationTime(elapsed_seconds.count());
    std::shuffle(std::begin(v), std::end(v), gen);
  }
}
BENCHMARK(StdSort)->Arg(10)->Arg(1000)->Arg(1'000'000)->UseManualTime();

Is this the right way to benchmark sorting algorithms using Google Benchmark? Is there a better approach?

0 Answers
Related