attributes_hashmap_benchmark.cc 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. #include <benchmark/benchmark.h>
  4. #include <stddef.h>
  5. #include <stdint.h>
  6. #include <algorithm>
  7. #include <functional>
  8. #include <memory>
  9. #include <mutex>
  10. #include <thread>
  11. #include <vector>
  12. #include "opentelemetry/nostd/function_ref.h"
  13. #include "opentelemetry/sdk/metrics/aggregation/aggregation.h"
  14. #include "opentelemetry/sdk/metrics/aggregation/drop_aggregation.h"
  15. #include "opentelemetry/sdk/metrics/state/attributes_hashmap.h"
  16. #include "opentelemetry/sdk/metrics/view/attributes_processor.h"
  17. using namespace opentelemetry::sdk::metrics;
  18. constexpr size_t MAX_THREADS = 500;
  19. namespace
  20. {
  21. void BM_AttributseHashMap(benchmark::State &state)
  22. {
  23. AttributesHashMap hash_map;
  24. std::vector<std::thread> workers;
  25. std::vector<MetricAttributes> attributes = {{{"k1", "v1"}, {"k2", "v2"}},
  26. {{"k1", "v1"}, {"k2", "v2"}, {"k3", "v3"}}};
  27. std::mutex m;
  28. auto work = [&attributes, &hash_map, &m](const size_t i) {
  29. std::function<std::unique_ptr<Aggregation>()> create_default_aggregation =
  30. []() -> std::unique_ptr<Aggregation> {
  31. return std::unique_ptr<Aggregation>(new DropAggregation);
  32. };
  33. m.lock();
  34. hash_map.GetOrSetDefault(attributes[i % 2], create_default_aggregation)
  35. ->Aggregate(static_cast<int64_t>(1));
  36. benchmark::DoNotOptimize(hash_map.Has(attributes[i % 2]));
  37. m.unlock();
  38. };
  39. while (state.KeepRunning())
  40. {
  41. for (size_t i = 0; i < MAX_THREADS; i++)
  42. {
  43. workers.push_back(std::thread(work, i));
  44. }
  45. }
  46. for (auto &t : workers)
  47. {
  48. t.join();
  49. }
  50. }
  51. BENCHMARK(BM_AttributseHashMap);
  52. } // namespace
  53. BENCHMARK_MAIN();