spinlock_benchmark.cc 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2018 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // See also //absl/synchronization:mutex_benchmark for a comparison of SpinLock
  15. // and Mutex performance under varying levels of contention.
  16. #include "absl/base/internal/raw_logging.h"
  17. #include "absl/base/internal/scheduling_mode.h"
  18. #include "absl/base/internal/spinlock.h"
  19. #include "absl/synchronization/internal/create_thread_identity.h"
  20. #include "benchmark/benchmark.h"
  21. namespace {
  22. template <absl::base_internal::SchedulingMode scheduling_mode>
  23. static void BM_SpinLock(benchmark::State& state) {
  24. // Ensure a ThreadIdentity is installed.
  25. ABSL_INTERNAL_CHECK(
  26. absl::synchronization_internal::GetOrCreateCurrentThreadIdentity() !=
  27. nullptr,
  28. "GetOrCreateCurrentThreadIdentity() failed");
  29. static auto* spinlock = new absl::base_internal::SpinLock(scheduling_mode);
  30. for (auto _ : state) {
  31. absl::base_internal::SpinLockHolder holder(spinlock);
  32. }
  33. }
  34. BENCHMARK_TEMPLATE(BM_SpinLock,
  35. absl::base_internal::SCHEDULE_KERNEL_ONLY)
  36. ->UseRealTime()
  37. ->Threads(1)
  38. ->ThreadPerCpu();
  39. BENCHMARK_TEMPLATE(BM_SpinLock,
  40. absl::base_internal::SCHEDULE_COOPERATIVE_AND_KERNEL)
  41. ->UseRealTime()
  42. ->Threads(1)
  43. ->ThreadPerCpu();
  44. } // namespace