| // SPDX-FileCopyrightText: The Eigen Authors | |
| // SPDX-License-Identifier: MPL-2.0 | |
| #include <cmath> | |
| #include <cstdint> | |
| #include <limits> | |
| #include <random> | |
| #include <benchmark/benchmark.h> | |
| #include <Eigen/Core> | |
| // mode: 0 = all normal, 1 = one subnormal per 64 coefficients, 2 = all subnormal. | |
| // Modes 3, 4 and 5 use independently placed zeros with probabilities 1%, 10% and 50%. | |
| static void BM_CbrtDouble(benchmark::State& state) { | |
| using Eigen::Index; | |
| const Index size = state.range(0); | |
| const int mode = static_cast<int>(state.range(1)); | |
| Eigen::ArrayXd input(size), output(size); | |
| std::mt19937_64 rng(86015); | |
| std::mt19937_64 positions(16703); | |
| constexpr int zero_percentages[] = {1, 10, 50}; | |
| constexpr uint64_t fraction_mask = (uint64_t(1) << 52) - 1; | |
| for (Index i = 0; i < size; ++i) { | |
| const uint64_t raw = rng(); | |
| const uint64_t fraction = raw & fraction_mask; | |
| const uint64_t sign = raw & (uint64_t(1) << 63); | |
| const uint64_t normal_exponent = 1 + rng() % 2046; | |
| const bool subnormal = mode == 2 || (mode == 1 && i % 64 == 0); | |
| const bool zero = mode >= 3 && positions() % 100 < zero_percentages[mode - 3]; | |
| uint64_t magnitude = (normal_exponent << 52) | fraction; | |
| if (subnormal) magnitude = fraction | 1; | |
| if (zero) magnitude = 0; | |
| input[i] = Eigen::numext::bit_cast<double>(sign | magnitude); | |
| } | |
| output = input.cbrt(); | |
| for (Index i = 0; i < size; ++i) { | |
| const double reference = std::cbrt(input[i]); | |
| const bool correct = | |
| reference == 0.0 ? Eigen::numext::bit_cast<uint64_t>(output[i]) == Eigen::numext::bit_cast<uint64_t>(reference) | |
| : std::abs((output[i] - reference) / reference) <= 8 * std::numeric_limits<double>::epsilon(); | |
| if (!correct) { | |
| state.SkipWithError("cbrt output differs from the scalar reference"); | |
| return; | |
| } | |
| } | |
| for (auto _ : state) { | |
| benchmark::DoNotOptimize(input.data()); | |
| output = input.cbrt(); | |
| benchmark::DoNotOptimize(output.data()); | |
| benchmark::ClobberMemory(); | |
| } | |
| state.SetItemsProcessed(state.iterations() * size); | |
| } | |
| BENCHMARK(BM_CbrtDouble)->ArgsProduct({{1024, 16384, 262144}, {0, 1, 2, 3, 4, 5}})->ArgNames({"size", "mode"}); |