xref: /aosp_15_r20/external/abseil-cpp/absl/synchronization/blocking_counter_benchmark.cc (revision 9356374a3709195abf420251b3e825997ff56c0f)
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 
15 #include <limits>
16 
17 #include "absl/base/no_destructor.h"
18 #include "absl/synchronization/blocking_counter.h"
19 #include "absl/synchronization/internal/thread_pool.h"
20 #include "benchmark/benchmark.h"
21 
22 namespace {
23 
BM_BlockingCounter_SingleThread(benchmark::State & state)24 void BM_BlockingCounter_SingleThread(benchmark::State& state) {
25   for (auto _ : state) {
26     int iterations = state.range(0);
27     absl::BlockingCounter counter{iterations};
28     for (int i = 0; i < iterations; ++i) {
29       counter.DecrementCount();
30     }
31     counter.Wait();
32   }
33 }
34 BENCHMARK(BM_BlockingCounter_SingleThread)
35     ->ArgName("iterations")
36     ->Arg(2)
37     ->Arg(4)
38     ->Arg(16)
39     ->Arg(64)
40     ->Arg(256);
41 
BM_BlockingCounter_DecrementCount(benchmark::State & state)42 void BM_BlockingCounter_DecrementCount(benchmark::State& state) {
43   static absl::NoDestructor<absl::BlockingCounter> counter(
44       std::numeric_limits<int>::max());
45   for (auto _ : state) {
46     counter->DecrementCount();
47   }
48 }
49 BENCHMARK(BM_BlockingCounter_DecrementCount)
50     ->Threads(2)
51     ->Threads(4)
52     ->Threads(6)
53     ->Threads(8)
54     ->Threads(10)
55     ->Threads(12)
56     ->Threads(16)
57     ->Threads(32)
58     ->Threads(64)
59     ->Threads(128);
60 
BM_BlockingCounter_Wait(benchmark::State & state)61 void BM_BlockingCounter_Wait(benchmark::State& state) {
62   int num_threads = state.range(0);
63   absl::synchronization_internal::ThreadPool pool(num_threads);
64   for (auto _ : state) {
65     absl::BlockingCounter counter{num_threads};
66     pool.Schedule([num_threads, &counter, &pool]() {
67       for (int i = 0; i < num_threads; ++i) {
68         pool.Schedule([&counter]() { counter.DecrementCount(); });
69       }
70     });
71     counter.Wait();
72   }
73 }
74 BENCHMARK(BM_BlockingCounter_Wait)
75     ->ArgName("threads")
76     ->Arg(2)
77     ->Arg(4)
78     ->Arg(8)
79     ->Arg(16)
80     ->Arg(32)
81     ->Arg(64)
82     ->Arg(128);
83 
84 }  // namespace
85