| 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 |
|
| 20 |
int global_value = 42; |
| 21 |
std::mutex m; |
| 22 |
std::shared_mutex sm; |
| 23 |
|
| 24 |
static void BM_shared_mutex(benchmark::State& state) { |
| 25 |
for (auto _ : state) { |
| 26 |
std::shared_lock<std::shared_mutex> lock(sm); |
| 27 |
benchmark::DoNotOptimize(global_value); |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
static void BM_mutex(benchmark::State& state) { |
| 32 |
for (auto _ : state) { |
| 33 |
std::lock_guard<std::mutex> lock(m); |
| 34 |
benchmark::DoNotOptimize(global_value); |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
BENCHMARK(BM_shared_mutex)->Threads(1)->Threads(2)->Threads(4)->Threads(8)->Threads(32); |
| 39 |
BENCHMARK(BM_mutex)->Threads(1)->Threads(2)->Threads(4)->Threads(8)->Threads(32); |
| 40 |
|
| 41 |
BENCHMARK_MAIN(); |