| 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, c++17 |
| 10 | |
| 11 | #include <algorithm> |
| 12 | #include <cstddef> |
| 13 | #include <deque> |
| 14 | #include <iterator> |
| 15 | #include <list> |
| 16 | #include <random> |
| 17 | #include <string> |
| 18 | #include <vector> |
| 19 | |
| 20 | #include "benchmark/benchmark.h" |
| 21 | #include "../../GenerateInput.h" |
| 22 | |
| 23 | int main(int argc, char** argv) { |
| 24 | auto std_sample = [](auto first, auto last, auto out, auto n, auto& rng) { |
| 25 | return std::sample(first, last, out, n, rng); |
| 26 | }; |
| 27 | |
| 28 | // {std,ranges}::sample(normal container) |
| 29 | { |
| 30 | auto bm = []<class Container>(std::string name, auto sample) { |
| 31 | benchmark::RegisterBenchmark( |
| 32 | name, |
| 33 | [sample](auto& st) { |
| 34 | std::size_t const size = st.range(0); |
| 35 | using ValueType = typename Container::value_type; |
| 36 | Container c; |
| 37 | std::generate_n(std::back_inserter(c), size, [] { return Generate<ValueType>::random(); }); |
| 38 | |
| 39 | std::vector<ValueType> out(size); |
| 40 | auto const n = size / 4; // sample 1/4 of the range |
| 41 | std::mt19937 rng; |
| 42 | |
| 43 | for ([[maybe_unused]] auto _ : st) { |
| 44 | benchmark::DoNotOptimize(c); |
| 45 | benchmark::DoNotOptimize(out); |
| 46 | auto result = sample(c.begin(), c.end(), out.begin(), n, rng); |
| 47 | benchmark::DoNotOptimize(result); |
| 48 | } |
| 49 | }) |
| 50 | ->Arg(32) |
| 51 | ->Arg(1024) |
| 52 | ->Arg(8192); |
| 53 | }; |
| 54 | bm.operator()<std::vector<int>>(name: "std::sample(vector<int>)" , sample: std_sample); |
| 55 | bm.operator()<std::deque<int>>(name: "std::sample(deque<int>)" , sample: std_sample); |
| 56 | bm.operator()<std::list<int>>(name: "std::sample(list<int>)" , sample: std_sample); |
| 57 | bm.operator()<std::vector<int>>("rng::sample(vector<int>)" , std::ranges::sample); |
| 58 | bm.operator()<std::deque<int>>("rng::sample(deque<int>)" , std::ranges::sample); |
| 59 | bm.operator()<std::list<int>>("rng::sample(list<int>)" , std::ranges::sample); |
| 60 | } |
| 61 | |
| 62 | benchmark::Initialize(&argc, argv); |
| 63 | benchmark::RunSpecifiedBenchmarks(); |
| 64 | benchmark::Shutdown(); |
| 65 | return 0; |
| 66 | } |
| 67 | |