bench.h raw

   1  // Copyright (c) 2015-2022 The Limenka developers
   2  // Distributed under the MIT software license, see the accompanying
   3  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
   4  
   5  #ifndef LIMENKA_BENCH_BENCH_H
   6  #define LIMENKA_BENCH_BENCH_H
   7  
   8  #include <bench/nanobench.h> // IWYU pragma: export
   9  #include <util/fs.h>
  10  #include <util/macros.h>
  11  
  12  #include <chrono>
  13  #include <cstdint>
  14  #include <functional>
  15  #include <map>
  16  #include <string>
  17  #include <utility>
  18  #include <vector>
  19  
  20  /*
  21   * Usage:
  22  
  23  static void NameOfYourBenchmarkFunction(benchmark::Bench& bench)
  24  {
  25      ...do any setup needed...
  26  
  27      bench.run([&] {
  28           ...do stuff you want to time; refer to src/bench/nanobench.h
  29              for more information and the options that can be passed here...
  30      });
  31  
  32      ...do any cleanup needed...
  33  }
  34  
  35  BENCHMARK(NameOfYourBenchmarkFunction);
  36  
  37   */
  38  
  39  namespace benchmark {
  40  
  41  using ankerl::nanobench::Bench;
  42  
  43  typedef std::function<void(Bench&)> BenchFunction;
  44  
  45  enum PriorityLevel : uint8_t
  46  {
  47      LOW = 1 << 0,
  48      HIGH = 1 << 2,
  49  };
  50  
  51  // List priority labels, comma-separated and sorted by increasing priority
  52  std::string ListPriorities();
  53  uint8_t StringToPriority(const std::string& str);
  54  
  55  struct Args {
  56      bool is_list_only;
  57      bool sanity_check;
  58      std::chrono::milliseconds min_time;
  59      std::vector<double> asymptote;
  60      fs::path output_csv;
  61      fs::path output_json;
  62      std::string regex_filter;
  63      uint8_t priority;
  64      std::vector<std::string> setup_args;
  65  };
  66  
  67  class BenchRunner
  68  {
  69      // maps from "name" -> (function, priority_level)
  70      typedef std::map<std::string, std::pair<BenchFunction, PriorityLevel>> BenchmarkMap;
  71      static BenchmarkMap& benchmarks();
  72  
  73  public:
  74      BenchRunner(std::string name, BenchFunction func, PriorityLevel level);
  75  
  76      static void RunAll(const Args& args);
  77  };
  78  } // namespace benchmark
  79  
  80  // BENCHMARK(foo) expands to:  benchmark::BenchRunner bench_11foo("foo", foo, priority_level);
  81  #define BENCHMARK(n, priority_level) \
  82      benchmark::BenchRunner PASTE2(bench_, PASTE2(__LINE__, n))(STRINGIZE(n), n, priority_level);
  83  
  84  #endif // LIMENKA_BENCH_BENCH_H
  85