NotificationQueueBenchmark.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Copyright 2018-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/Benchmark.h>
  17. #include <folly/io/async/EventBase.h>
  18. #include <folly/synchronization/Baton.h>
  19. #include <condition_variable>
  20. #include <mutex>
  21. #include <thread>
  22. using namespace folly;
  23. static size_t constexpr kMaxRead = 20;
  24. void runTest(int iters, int numThreads) {
  25. BenchmarkSuspender susp;
  26. EventBase evb;
  27. evb.setMaxReadAtOnce(kMaxRead);
  28. std::mutex m;
  29. std::condition_variable cv;
  30. int numRunning = 0;
  31. int numProcessed = 0;
  32. int numTotal = iters * numThreads;
  33. std::vector<std::thread> threads;
  34. for (int i = 0; i < numThreads; i++) {
  35. threads.push_back(std::thread([&]() mutable {
  36. // wait for all the threads to start up
  37. bool notifyAll = false;
  38. {
  39. std::lock_guard<std::mutex> lk(m);
  40. if (++numRunning == numThreads) {
  41. notifyAll = true;
  42. susp.dismiss();
  43. }
  44. }
  45. if (notifyAll) {
  46. cv.notify_all();
  47. } else {
  48. std::unique_lock<std::mutex> lk(m);
  49. cv.wait(lk, [&]() { return numRunning == numThreads; });
  50. }
  51. for (auto j = 0; j < iters; j++) {
  52. evb.runInEventBaseThread([&]() mutable {
  53. if (++numProcessed == numTotal) {
  54. evb.terminateLoopSoon();
  55. ;
  56. }
  57. });
  58. }
  59. }));
  60. }
  61. evb.loopForever();
  62. susp.rehire();
  63. for (auto& t : threads) {
  64. t.join();
  65. }
  66. }
  67. BENCHMARK_PARAM(runTest, 1)
  68. BENCHMARK_PARAM(runTest, 2)
  69. BENCHMARK_PARAM(runTest, 4)
  70. BENCHMARK_PARAM(runTest, 8)
  71. BENCHMARK_PARAM(runTest, 16)
  72. BENCHMARK_PARAM(runTest, 32)
  73. int main(int argc, char* argv[]) {
  74. gflags::ParseCommandLineFlags(&argc, &argv, true);
  75. folly::runBenchmarks();
  76. return 0;
  77. }