folly copyright 2015 -> copyright 2016
[folly.git] / folly / experimental / test / RefCountBenchmark.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 #include <thread>
17
18 #include <folly/Benchmark.h>
19 #include <folly/experimental/RCURefCount.h>
20 #include <folly/experimental/TLRefCount.h>
21
22 namespace folly {
23
24 template <typename Counter>
25 void shutdown(Counter&) {
26 }
27
28 void shutdown(RCURefCount& c) {
29   c.useGlobal();
30   --c;
31 }
32
33 void shutdown(TLRefCount& c) {
34   c.useGlobal();
35   --c;
36 }
37
38 template <typename Counter, size_t threadCount>
39 void benchmark(size_t n) {
40   Counter x;
41
42   std::vector<std::thread> ts;
43
44   for (size_t t = 0; t < threadCount; ++t) {
45     ts.emplace_back([&]() {
46         for (size_t i = 0; i < n; ++i) {
47           ++x;
48         }
49         for (size_t i = 0; i < n; ++i) {
50           --x;
51         }
52       });
53   }
54
55   for (auto& t: ts) {
56     t.join();
57   }
58
59   shutdown(x);
60 }
61
62 BENCHMARK(atomicOneThread, n) {
63   benchmark<std::atomic<RCURefCount::Int>, 1>(n);
64 }
65
66 BENCHMARK(atomicFourThreads, n) {
67   benchmark<std::atomic<RCURefCount::Int>, 4>(n);
68 }
69
70 BENCHMARK(RCURefCountOneThread, n) {
71   benchmark<RCURefCount, 1>(n);
72 }
73
74 BENCHMARK(RCURefCountFourThreads, n) {
75   benchmark<RCURefCount, 4>(n);
76 }
77
78 BENCHMARK(TLRefCountOneThread, n) {
79   benchmark<TLRefCount, 1>(n);
80 }
81
82 BENCHMARK(TLRefCountFourThreads, n) {
83   benchmark<TLRefCount, 4>(n);
84 }
85
86 }
87
88 int main(int argc, char** argv) {
89   gflags::ParseCommandLineFlags(&argc, &argv, true);
90   gflags::SetCommandLineOptionWithMode(
91     "bm_min_usec", "100000", gflags::SET_FLAG_IF_DEFAULT
92   );
93
94   folly::runBenchmarks();
95
96   return 0;
97 }