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-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | |
9 | // UNSUPPORTED: c++03, c++11, c++14 |
10 | |
11 | #include <array> |
12 | #include <benchmark/benchmark.h> |
13 | #include <cstring> |
14 | #include <numeric> |
15 | #include <random> |
16 | |
17 | template <class T> |
18 | static 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 | |
26 | static void bm_gcd_random(benchmark::State& state) { |
27 | std::array data = generate<int>(); |
28 | while (state.KeepRunningBatch(n: data.size() * data.size())) |
29 | for (auto v0 : data) |
30 | for (auto v1 : data) |
31 | benchmark::DoNotOptimize(value: std::gcd(m: v0, n: v1)); |
32 | } |
33 | BENCHMARK(bm_gcd_random); |
34 | |
35 | static void bm_gcd_trivial(benchmark::State& state) { |
36 | int lhs = ~static_cast<int>(0), rhs = 1; |
37 | for (auto _ : state) { |
38 | benchmark::DoNotOptimize(value&: lhs); |
39 | benchmark::DoNotOptimize(value&: rhs); |
40 | benchmark::DoNotOptimize(value: std::gcd(m: lhs, n: rhs)); |
41 | } |
42 | } |
43 | BENCHMARK(bm_gcd_trivial); |
44 | |
45 | static void bm_gcd_complex(benchmark::State& state) { |
46 | long long lhs = 2971215073; |
47 | long long rhs = 1836311903; |
48 | for (auto _ : state) { |
49 | benchmark::DoNotOptimize(value&: lhs); |
50 | benchmark::DoNotOptimize(value&: rhs); |
51 | benchmark::DoNotOptimize(value: std::gcd(m: lhs, n: rhs)); |
52 | } |
53 | } |
54 | BENCHMARK(bm_gcd_complex); |
55 | |
56 | BENCHMARK_MAIN(); |
57 | |