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 <charconv> |
13 | #include <random> |
14 | |
15 | #include "benchmark/benchmark.h" |
16 | #include "test_macros.h" |
17 | |
18 | static const std::array<unsigned, 1000> input = [] { |
19 | std::mt19937 generator; |
20 | std::uniform_int_distribution<unsigned> distribution(0, std::numeric_limits<unsigned>::max()); |
21 | std::array<unsigned, 1000> result; |
22 | std::generate_n(result.begin(), result.size(), [&] { return distribution(generator); }); |
23 | return result; |
24 | }(); |
25 | |
26 | static void BM_to_chars_good(benchmark::State& state) { |
27 | char buffer[128]; |
28 | int base = state.range(0); |
29 | while (state.KeepRunningBatch(input.size())) |
30 | for (auto value : input) |
31 | benchmark::DoNotOptimize(std::to_chars(buffer, &buffer[128], value, base)); |
32 | } |
33 | BENCHMARK(BM_to_chars_good)->DenseRange(2, 36, 1); |
34 | |
35 | static void BM_to_chars_bad(benchmark::State& state) { |
36 | char buffer[128]; |
37 | int base = state.range(0); |
38 | struct sample { |
39 | unsigned size; |
40 | unsigned value; |
41 | }; |
42 | std::array<sample, 1000> data; |
43 | // Assume the failure occurs, on average, halfway during the conversion. |
44 | std::transform(input.begin(), input.end(), data.begin(), [&](unsigned value) { |
45 | std::to_chars_result result = std::to_chars(first: buffer, last: &buffer[128], value: value, base: base); |
46 | return sample{unsigned((result.ptr - buffer) / 2), value}; |
47 | }); |
48 | |
49 | while (state.KeepRunningBatch(data.size())) |
50 | for (auto element : data) |
51 | benchmark::DoNotOptimize(std::to_chars(buffer, &buffer[element.size], element.value, base)); |
52 | } |
53 | BENCHMARK(BM_to_chars_bad)->DenseRange(2, 36, 1); |
54 | |
55 | BENCHMARK_MAIN(); |
56 | |