Skip to content

Instantly share code, notes, and snippets.

@dtoma
Created December 7, 2018 09:14
Show Gist options
  • Select an option

  • Save dtoma/71a6e945c6557d2d1ad3048626ca0802 to your computer and use it in GitHub Desktop.

Select an option

Save dtoma/71a6e945c6557d2d1ad3048626ca0802 to your computer and use it in GitHub Desktop.
Bench lib c++
/* Simple benchmarking library
- Run `f()` in increasing batch sizes
- report the estimated time of `f()` by doing a linear regression
- Output a vega-lite JSON file for visualization
Inspiration:
- https://blog.janestreet.com/core_bench-micro-benchmarking-for-ocaml/
- http://www.serpentine.com/blog/2009/09/29/criterion-a-new-benchmarking-library-for-haskell/
- https://vega.github.io/vega-lite/examples/bar.html
*/
// Once C++20 concepts are available:
// #include <concepts>
// void benchmark(std::Invocable auto fun) {}
#include <algorithm>
#include <array>
#include <chrono>
#include <vector>
template <typename Invokable>
auto measure(Invokable&& fun, int const nb_runs) {
std::vector<int> durations(nb_runs);
for (int i = 0; i < nb_runs; i++) {
auto start = std::chrono::high_resolution_clock::now();
fun();
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = end - start;
durations[i] = diff.count();
}
auto [min, max] = std::minmax_element(std::begin(durations), std::end(durations));
return {min, max, 0};
}
template <typename Invokable>
void benchmark(Invokable&& fun) {
std::array<int const, 5> const batch_sizes = {1, 10, 100, 1000, 10000};
for (auto const batch_size : batch_sizes) {
auto [low, high, reg] = measure(fun, batch_size);
}
}
int main() {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment