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 <list>
15#include <string>
16#include <vector>
17
18#include <benchmark/benchmark.h>
19
20int main(int argc, char** argv) {
21 auto std_for_each = [](auto first, auto last, auto f) { return std::for_each(first, last, f); };
22
23 // {std,ranges}::for_each
24 {
25 auto bm = []<class Container>(std::string name, auto for_each) {
26 benchmark::RegisterBenchmark(
27 name,
28 [for_each](auto& st) {
29 std::size_t const size = st.range(0);
30 Container c(size, 1);
31 auto first = c.begin();
32 auto last = c.end();
33
34 for ([[maybe_unused]] auto _ : st) {
35 benchmark::DoNotOptimize(c);
36 auto result = for_each(first, last, [](int& x) { x = std::clamp(x, 10, 100); });
37 benchmark::DoNotOptimize(result);
38 }
39 })
40 ->Arg(8)
41 ->Arg(32)
42 ->Arg(50) // non power-of-two
43 ->Arg(8192)
44 ->Arg(1 << 20);
45 };
46 bm.operator()<std::vector<int>>("std::for_each(vector<int>)", std_for_each);
47 bm.operator()<std::deque<int>>("std::for_each(deque<int>)", std_for_each);
48 bm.operator()<std::list<int>>("std::for_each(list<int>)", std_for_each);
49 bm.operator()<std::vector<int>>("rng::for_each(vector<int>)", std::ranges::for_each);
50 bm.operator()<std::deque<int>>("rng::for_each(deque<int>)", std::ranges::for_each);
51 bm.operator()<std::list<int>>("rng::for_each(list<int>)", std::ranges::for_each);
52 }
53
54 benchmark::Initialize(&argc, argv);
55 benchmark::RunSpecifiedBenchmarks();
56 benchmark::Shutdown();
57 return 0;
58}
59

source code of libcxx/test/benchmarks/algorithms/nonmodifying/for_each.bench.cpp