[MemProf] Templatize CallStackRadixTreeBuilder (NFC) (#117014)
[llvm-project.git] / libcxx / test / benchmarks / shared_mutex_vs_mutex.bench.cpp
blob84a49a8d07d04e1ac49a6fd9a2df748c584537b3
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 //===----------------------------------------------------------------------===//
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.
15 #include <atomic>
16 #include <mutex>
17 #include <numeric>
18 #include <shared_mutex>
19 #include <thread>
21 #include "benchmark/benchmark.h"
23 int global_value = 42;
24 std::mutex m;
25 std::shared_mutex sm;
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);
44 BENCHMARK_MAIN();