57 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#include <array>12#include <benchmark/benchmark.h>13#include <cstring>14#include <numeric>15#include <random>16 17template <class T>18static std::array<T, 1000> generate(std::uniform_int_distribution<T> distribution = std::uniform_int_distribution<T>{19 std::numeric_limits<T>::min() + 1, std::numeric_limits<T>::max()}) {20 std::mt19937 generator;21 std::array<T, 1000> result;22 std::generate_n(result.begin(), result.size(), [&] { return distribution(generator); });23 return result;24}25 26static void bm_gcd_random(benchmark::State& state) {27 std::array data = generate<int>();28 while (state.KeepRunningBatch(data.size() * data.size()))29 for (auto v0 : data)30 for (auto v1 : data)31 benchmark::DoNotOptimize(std::gcd(v0, v1));32}33BENCHMARK(bm_gcd_random);34 35static void bm_gcd_trivial(benchmark::State& state) {36 int lhs = ~static_cast<int>(0), rhs = 1;37 for (auto _ : state) {38 benchmark::DoNotOptimize(lhs);39 benchmark::DoNotOptimize(rhs);40 benchmark::DoNotOptimize(std::gcd(lhs, rhs));41 }42}43BENCHMARK(bm_gcd_trivial);44 45static void bm_gcd_complex(benchmark::State& state) {46 long long lhs = 2971215073;47 long long rhs = 1836311903;48 for (auto _ : state) {49 benchmark::DoNotOptimize(lhs);50 benchmark::DoNotOptimize(rhs);51 benchmark::DoNotOptimize(std::gcd(lhs, rhs));52 }53}54BENCHMARK(bm_gcd_complex);55 56BENCHMARK_MAIN();57