1 //===----------------------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // UNSUPPORTED: c++03, c++11, c++14
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.
18 #include <shared_mutex>
21 #include "benchmark/benchmark.h"
23 int global_value
= 42;
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
);
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
);
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);