1 | //===----------------------------------------------------------------------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | |
9 | // UNSUPPORTED: c++03, c++11, c++14 |
10 | |
11 | // This benchmark compares the performance of std::mutex and std::shared_mutex in contended scenarios. |
12 | // it's meant to establish a baseline overhead for std::shared_mutex and std::mutex, and to help inform decisions about |
13 | // which mutex to use when selecting a mutex type for a given use case. |
14 | |
15 | #include <atomic> |
16 | #include <mutex> |
17 | #include <numeric> |
18 | #include <shared_mutex> |
19 | #include <thread> |
20 | |
21 | #include "benchmark/benchmark.h" |
22 | |
23 | int global_value = 42; |
24 | std::mutex m; |
25 | std::shared_mutex sm; |
26 | |
27 | static void BM_shared_mutex(benchmark::State& state) { |
28 | for (auto _ : state) { |
29 | std::shared_lock<std::shared_mutex> lock(sm); |
30 | benchmark::DoNotOptimize(global_value); |
31 | } |
32 | } |
33 | |
34 | static void BM_mutex(benchmark::State& state) { |
35 | for (auto _ : state) { |
36 | std::lock_guard<std::mutex> lock(m); |
37 | benchmark::DoNotOptimize(global_value); |
38 | } |
39 | } |
40 | |
41 | BENCHMARK(BM_shared_mutex)->Threads(1)->Threads(2)->Threads(4)->Threads(8)->Threads(32); |
42 | BENCHMARK(BM_mutex)->Threads(1)->Threads(2)->Threads(4)->Threads(8)->Threads(32); |
43 | |
44 | BENCHMARK_MAIN(); |
45 | |