CallOnceBenchmark.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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/CallOnce.h>
  17. #include <deque>
  18. #include <mutex>
  19. #include <thread>
  20. #include <folly/Benchmark.h>
  21. #include <glog/logging.h>
  22. DEFINE_int32(threads, 16, "benchmark concurrency");
  23. template <typename CallOnceFunc>
  24. void bm_impl(CallOnceFunc&& fn, size_t iters) {
  25. std::deque<std::thread> threads;
  26. for (size_t i = 0u; i < size_t(FLAGS_threads); ++i) {
  27. threads.emplace_back([&fn, iters] {
  28. for (size_t j = 0u; j < iters; ++j) {
  29. fn();
  30. }
  31. });
  32. }
  33. for (std::thread& t : threads) {
  34. t.join();
  35. }
  36. }
  37. BENCHMARK(StdCallOnceBench, iters) {
  38. std::once_flag flag;
  39. int out = 0;
  40. bm_impl([&] { std::call_once(flag, [&] { ++out; }); }, iters);
  41. CHECK_EQ(1, out);
  42. }
  43. BENCHMARK(FollyCallOnceBench, iters) {
  44. folly::once_flag flag;
  45. int out = 0;
  46. bm_impl([&] { folly::call_once(flag, [&] { ++out; }); }, iters);
  47. CHECK_EQ(1, out);
  48. }
  49. /*
  50. $ call_once_benchmark --bm_min_iters=100000000 --threads=16
  51. ============================================================================
  52. folly/synchronization/test/CallOnceBenchmark.cpprelative time/iter iters/s
  53. ============================================================================
  54. StdCallOnceBench 2.40ns 416.78M
  55. FollyCallOnceBench 651.94ps 1.53G
  56. ============================================================================
  57. */
  58. int main(int argc, char** argv) {
  59. gflags::ParseCommandLineFlags(&argc, &argv, true);
  60. folly::runBenchmarks();
  61. return 0;
  62. }