BatonBenchmark.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright 2016-present 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. #include <folly/synchronization/Baton.h>
  17. #include <thread>
  18. #include <folly/Benchmark.h>
  19. #include <folly/portability/Semaphore.h>
  20. #include <folly/synchronization/test/BatonTestHelpers.h>
  21. #include <folly/test/DeterministicSchedule.h>
  22. using namespace folly;
  23. using namespace folly::test;
  24. using folly::detail::EmulatedFutexAtomic;
  25. BENCHMARK(baton_pingpong_blocking, iters) {
  26. run_pingpong_test<true, std::atomic>(iters);
  27. }
  28. BENCHMARK(baton_pingpong_nonblocking, iters) {
  29. run_pingpong_test<false, std::atomic>(iters);
  30. }
  31. BENCHMARK_DRAW_LINE();
  32. BENCHMARK(baton_pingpong_emulated_futex_blocking, iters) {
  33. run_pingpong_test<true, EmulatedFutexAtomic>(iters);
  34. }
  35. BENCHMARK(baton_pingpong_emulated_futex_nonblocking, iters) {
  36. run_pingpong_test<false, EmulatedFutexAtomic>(iters);
  37. }
  38. BENCHMARK_DRAW_LINE();
  39. BENCHMARK(posix_sem_pingpong, iters) {
  40. sem_t sems[3];
  41. sem_t* a = sems + 0;
  42. sem_t* b = sems + 2; // to get it on a different cache line
  43. sem_init(a, 0, 0);
  44. sem_init(b, 0, 0);
  45. auto thr = std::thread([=] {
  46. for (size_t i = 0; i < iters; ++i) {
  47. sem_wait(a);
  48. sem_post(b);
  49. }
  50. });
  51. for (size_t i = 0; i < iters; ++i) {
  52. sem_post(a);
  53. sem_wait(b);
  54. }
  55. thr.join();
  56. }
  57. // I am omitting a benchmark result snapshot because these microbenchmarks
  58. // mainly illustrate that PreBlockAttempts is very effective for rapid
  59. // handoffs. The performance of Baton and sem_t is essentially identical
  60. // to the required futex calls for the blocking case
  61. int main(int argc, char** argv) {
  62. gflags::ParseCommandLineFlags(&argc, &argv, true);
  63. folly::runBenchmarks();
  64. return 0;
  65. }