Add MicroLock as an alternative to MicroSpinLock
[folly.git] / folly / test / SmallLocksBenchmark.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/Benchmark.h>
18 #include <folly/SmallLocks.h>
19
20 BENCHMARK(MicroSpinLockUncontendedBenchmark, iters) {
21   folly::MicroSpinLock lock;
22   lock.init();
23   while (iters--) {
24     lock.lock();
25     lock.unlock();
26   }
27 }
28
29 BENCHMARK(PicoSpinLockUncontendedBenchmark, iters) {
30   // uint8_t would be more fair, but PicoSpinLock needs at lesat two bytes
31   folly::PicoSpinLock<uint16_t> lock;
32   lock.init();
33   while (iters--) {
34     lock.lock();
35     lock.unlock();
36   }
37 }
38
39 BENCHMARK(MicroLockUncontendedBenchmark, iters) {
40   folly::MicroLock lock;
41   lock.init();
42   while (iters--) {
43     lock.lock();
44     lock.unlock();
45   }
46 }
47
48 BENCHMARK(StdMutexUncontendedBenchmark, iters) {
49   std::mutex lock;
50   while (iters--) {
51     lock.lock();
52     lock.unlock();
53   }
54 }
55
56 struct VirtualBase {
57   virtual void foo() = 0;
58   virtual ~VirtualBase() {}
59 };
60
61 struct VirtualImpl : VirtualBase {
62   virtual void foo() { /* noop */
63   }
64   virtual ~VirtualImpl() {}
65 };
66
67 #ifndef __clang__
68 __attribute__((noinline, noclone)) VirtualBase* makeVirtual() {
69   return new VirtualImpl();
70 }
71
72 BENCHMARK(VirtualFunctionCall, iters) {
73   VirtualBase* vb = makeVirtual();
74   while (iters--) {
75     vb->foo();
76   }
77   delete vb;
78 }
79 #endif
80
81 int main(int argc, char** argv) {
82   gflags::ParseCommandLineFlags(&argc, &argv, true);
83   folly::runBenchmarks();
84   return 0;
85 }