8e8ee03d5331f9b77e90fcc783a67118e9c9aa8a
[folly.git] / folly / synchronization / test / BatonBenchmark.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <folly/synchronization/Baton.h>
18
19 #include <thread>
20
21 #include <folly/Benchmark.h>
22 #include <folly/portability/Semaphore.h>
23 #include <folly/synchronization/test/BatonTestHelpers.h>
24 #include <folly/test/DeterministicSchedule.h>
25
26 using namespace folly;
27 using namespace folly::test;
28 using folly::detail::EmulatedFutexAtomic;
29
30 typedef DeterministicSchedule DSched;
31
32 BENCHMARK(baton_pingpong_blocking, iters) {
33   run_pingpong_test<true, std::atomic>(iters);
34 }
35
36 BENCHMARK(baton_pingpong_nonblocking, iters) {
37   run_pingpong_test<false, std::atomic>(iters);
38 }
39
40 BENCHMARK_DRAW_LINE()
41
42 BENCHMARK(baton_pingpong_emulated_futex_blocking, iters) {
43   run_pingpong_test<true, EmulatedFutexAtomic>(iters);
44 }
45
46 BENCHMARK(baton_pingpong_emulated_futex_nonblocking, iters) {
47   run_pingpong_test<false, EmulatedFutexAtomic>(iters);
48 }
49
50 BENCHMARK_DRAW_LINE()
51
52 BENCHMARK(posix_sem_pingpong, iters) {
53   sem_t sems[3];
54   sem_t* a = sems + 0;
55   sem_t* b = sems + 2; // to get it on a different cache line
56
57   sem_init(a, 0, 0);
58   sem_init(b, 0, 0);
59   auto thr = std::thread([=] {
60     for (size_t i = 0; i < iters; ++i) {
61       sem_wait(a);
62       sem_post(b);
63     }
64   });
65   for (size_t i = 0; i < iters; ++i) {
66     sem_post(a);
67     sem_wait(b);
68   }
69   thr.join();
70 }
71
72 // I am omitting a benchmark result snapshot because these microbenchmarks
73 // mainly illustrate that PreBlockAttempts is very effective for rapid
74 // handoffs.  The performance of Baton and sem_t is essentially identical
75 // to the required futex calls for the blocking case
76
77 int main(int argc, char** argv) {
78   gflags::ParseCommandLineFlags(&argc, &argv, true);
79   folly::runBenchmarks();
80   return 0;
81 }