blocking_counter_benchmark.cc 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2021 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <limits>
  15. #include "absl/synchronization/blocking_counter.h"
  16. #include "absl/synchronization/internal/thread_pool.h"
  17. #include "benchmark/benchmark.h"
  18. namespace {
  19. void BM_BlockingCounter_SingleThread(benchmark::State& state) {
  20. for (auto _ : state) {
  21. int iterations = state.range(0);
  22. absl::BlockingCounter counter{iterations};
  23. for (int i = 0; i < iterations; ++i) {
  24. counter.DecrementCount();
  25. }
  26. counter.Wait();
  27. }
  28. }
  29. BENCHMARK(BM_BlockingCounter_SingleThread)
  30. ->ArgName("iterations")
  31. ->Arg(2)
  32. ->Arg(4)
  33. ->Arg(16)
  34. ->Arg(64)
  35. ->Arg(256);
  36. void BM_BlockingCounter_DecrementCount(benchmark::State& state) {
  37. static absl::BlockingCounter* counter =
  38. new absl::BlockingCounter{std::numeric_limits<int>::max()};
  39. for (auto _ : state) {
  40. counter->DecrementCount();
  41. }
  42. }
  43. BENCHMARK(BM_BlockingCounter_DecrementCount)
  44. ->Threads(2)
  45. ->Threads(4)
  46. ->Threads(6)
  47. ->Threads(8)
  48. ->Threads(10)
  49. ->Threads(12)
  50. ->Threads(16)
  51. ->Threads(32)
  52. ->Threads(64)
  53. ->Threads(128);
  54. void BM_BlockingCounter_Wait(benchmark::State& state) {
  55. int num_threads = state.range(0);
  56. absl::synchronization_internal::ThreadPool pool(num_threads);
  57. for (auto _ : state) {
  58. absl::BlockingCounter counter{num_threads};
  59. pool.Schedule([num_threads, &counter, &pool]() {
  60. for (int i = 0; i < num_threads; ++i) {
  61. pool.Schedule([&counter]() { counter.DecrementCount(); });
  62. }
  63. });
  64. counter.Wait();
  65. }
  66. }
  67. BENCHMARK(BM_BlockingCounter_Wait)
  68. ->ArgName("threads")
  69. ->Arg(2)
  70. ->Arg(4)
  71. ->Arg(8)
  72. ->Arg(16)
  73. ->Arg(32)
  74. ->Arg(64)
  75. ->Arg(128);
  76. } // namespace