fix flaky ConnectTFOTimeout and ConnectTFOFallbackTimeout tests
[folly.git] / folly / test / BatonBenchmark.cpp
1 /*
2  * Copyright 2016 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/Baton.h>
18
19 #include <semaphore.h>
20 #include <thread>
21
22 #include <gtest/gtest.h>
23
24 #include <folly/Benchmark.h>
25 #include <folly/portability/GFlags.h>
26 #include <folly/test/BatonTestHelpers.h>
27 #include <folly/test/DeterministicSchedule.h>
28
29 using namespace folly;
30 using namespace folly::test;
31 using folly::detail::EmulatedFutexAtomic;
32
33 typedef DeterministicSchedule DSched;
34
35 BENCHMARK(baton_pingpong, iters) { run_pingpong_test<std::atomic>(iters); }
36
37 BENCHMARK(baton_pingpong_emulated_futex, iters) {
38   run_pingpong_test<EmulatedFutexAtomic>(iters);
39 }
40
41 BENCHMARK(posix_sem_pingpong, iters) {
42   sem_t sems[3];
43   sem_t* a = sems + 0;
44   sem_t* b = sems + 2; // to get it on a different cache line
45
46   sem_init(a, 0, 0);
47   sem_init(b, 0, 0);
48   auto thr = std::thread([=] {
49     for (size_t i = 0; i < iters; ++i) {
50       sem_wait(a);
51       sem_post(b);
52     }
53   });
54   for (size_t i = 0; i < iters; ++i) {
55     sem_post(a);
56     sem_wait(b);
57   }
58   thr.join();
59 }
60
61 // I am omitting a benchmark result snapshot because these microbenchmarks
62 // mainly illustrate that PreBlockAttempts is very effective for rapid
63 // handoffs.  The performance of Baton and sem_t is essentially identical
64 // to the required futex calls for the blocking case
65
66 int main(int argc, char** argv) {
67   testing::InitGoogleTest(&argc, argv);
68   gflags::ParseCommandLineFlags(&argc, &argv, true);
69
70   auto rv = RUN_ALL_TESTS();
71   if (!rv && FLAGS_benchmark) {
72     folly::runBenchmarks();
73   }
74   return rv;
75 }