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

source code of libcxx/benchmarks/shared_mutex_vs_mutex.bench.cpp