You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.5 KiB

2 months ago
  1. #include <cstdlib>
  2. #include <map>
  3. #include "benchmark/benchmark.h"
  4. namespace {
  5. std::map<int, int> ConstructRandomMap(int size) {
  6. std::map<int, int> m;
  7. for (int i = 0; i < size; ++i) {
  8. m.insert(std::make_pair(std::rand() % size, std::rand() % size));
  9. }
  10. return m;
  11. }
  12. } // namespace
  13. // Basic version.
  14. static void BM_MapLookup(benchmark::State& state) {
  15. const int size = static_cast<int>(state.range(0));
  16. std::map<int, int> m;
  17. for (auto _ : state) {
  18. state.PauseTiming();
  19. m = ConstructRandomMap(size);
  20. state.ResumeTiming();
  21. for (int i = 0; i < size; ++i) {
  22. auto it = m.find(std::rand() % size);
  23. benchmark::DoNotOptimize(it);
  24. }
  25. }
  26. state.SetItemsProcessed(state.iterations() * size);
  27. }
  28. BENCHMARK(BM_MapLookup)->Range(1 << 3, 1 << 12);
  29. // Using fixtures.
  30. class MapFixture : public ::benchmark::Fixture {
  31. public:
  32. void SetUp(const ::benchmark::State& st) override {
  33. m = ConstructRandomMap(static_cast<int>(st.range(0)));
  34. }
  35. void TearDown(const ::benchmark::State&) override { m.clear(); }
  36. std::map<int, int> m;
  37. };
  38. BENCHMARK_DEFINE_F(MapFixture, Lookup)(benchmark::State& state) {
  39. const int size = static_cast<int>(state.range(0));
  40. for (auto _ : state) {
  41. for (int i = 0; i < size; ++i) {
  42. auto it = m.find(std::rand() % size);
  43. benchmark::DoNotOptimize(it);
  44. }
  45. }
  46. state.SetItemsProcessed(state.iterations() * size);
  47. }
  48. BENCHMARK_REGISTER_F(MapFixture, Lookup)->Range(1 << 3, 1 << 12);
  49. BENCHMARK_MAIN();