Michael Park | c6f5137 | 2020-08-11 22:48:02 | [diff] [blame] | 1 | // -*- C++ -*- |
| 2 | //===----------------------------------------------------------------------===// |
| 3 | // |
| 4 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 5 | // See https://llvm.org/LICENSE.txt for license information. |
| 6 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | |
| 10 | #ifndef BENCHMARK_VARIANT_BENCHMARKS_H |
| 11 | #define BENCHMARK_VARIANT_BENCHMARKS_H |
| 12 | |
| 13 | #include <array> |
| 14 | #include <cstddef> |
| 15 | #include <tuple> |
| 16 | #include <type_traits> |
| 17 | #include <variant> |
| 18 | |
| 19 | #include "benchmark/benchmark.h" |
| 20 | |
| 21 | #include "GenerateInput.h" |
| 22 | |
| 23 | namespace VariantBenchmarks { |
| 24 | |
| 25 | template <std::size_t I> |
| 26 | struct S { |
| 27 | static constexpr size_t v = I; |
| 28 | }; |
| 29 | |
| 30 | template <std::size_t N, std::size_t... Is> |
| 31 | static auto genVariants(std::index_sequence<Is...>) { |
Louis Dionne | 5aa03b6 | 2023-06-16 13:49:04 | [diff] [blame] | 32 | using V = std::variant<S<Is>...>; |
| 33 | using F = V (*)(); |
Michael Park | c6f5137 | 2020-08-11 22:48:02 | [diff] [blame] | 34 | static constexpr F fs[] = {[] { return V(std::in_place_index<Is>); }...}; |
| 35 | |
| 36 | std::array<V, N> result = {}; |
| 37 | for (auto& v : result) { |
| 38 | v = fs[getRandomInteger(0ul, sizeof...(Is) - 1)](); |
| 39 | } |
| 40 | |
| 41 | return result; |
| 42 | } |
| 43 | |
| 44 | template <std::size_t N, std::size_t Alts> |
| 45 | static void BM_Visit(benchmark::State& state) { |
| 46 | auto args = genVariants<N>(std::make_index_sequence<Alts>{}); |
| 47 | for (auto _ : state) { |
Louis Dionne | 5aa03b6 | 2023-06-16 13:49:04 | [diff] [blame] | 48 | benchmark::DoNotOptimize( |
| 49 | std::apply([](auto... vs) { return std::visit([](auto... is) { return (is.v + ... + 0); }, vs...); }, args)); |
Michael Park | c6f5137 | 2020-08-11 22:48:02 | [diff] [blame] | 50 | } |
| 51 | } |
| 52 | |
Louis Dionne | 953af0e | 2024-09-05 16:39:05 | [diff] [blame^] | 53 | } // namespace VariantBenchmarks |
Michael Park | c6f5137 | 2020-08-11 22:48:02 | [diff] [blame] | 54 | |
| 55 | #endif // BENCHMARK_VARIANT_BENCHMARKS_H |