49 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8 9// UNSUPPORTED: c++03, c++11, c++1410 11// This benchmark is very expensive and we don't want to run it on a regular basis,12// only to ensure the code doesn't rot.13// REQUIRES: enable-benchmarks=dry-run14 15// This benchmark compares the performance of std::mutex and std::shared_mutex in contended scenarios.16// it's meant to establish a baseline overhead for std::shared_mutex and std::mutex, and to help inform decisions about17// which mutex to use when selecting a mutex type for a given use case.18 19#include <atomic>20#include <mutex>21#include <numeric>22#include <shared_mutex>23#include <thread>24 25#include "benchmark/benchmark.h"26 27int global_value = 42;28std::mutex m;29std::shared_mutex sm;30 31static void BM_shared_mutex(benchmark::State& state) {32 for (auto _ : state) {33 std::shared_lock<std::shared_mutex> lock(sm);34 benchmark::DoNotOptimize(global_value);35 }36}37 38static void BM_mutex(benchmark::State& state) {39 for (auto _ : state) {40 std::lock_guard<std::mutex> lock(m);41 benchmark::DoNotOptimize(global_value);42 }43}44 45BENCHMARK(BM_shared_mutex)->Threads(1)->Threads(2)->Threads(4)->Threads(8)->Threads(32);46BENCHMARK(BM_mutex)->Threads(1)->Threads(2)->Threads(4)->Threads(8)->Threads(32);47 48BENCHMARK_MAIN();49