1 | //===----------------------------------------------------------------------===// |
2 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
3 | // See https://llvm.org/LICENSE.txt for license information. |
4 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
5 | // |
6 | //===----------------------------------------------------------------------===// |
7 | |
8 | #include <array> |
9 | #include <charconv> |
10 | #include <random> |
11 | |
12 | #include "benchmark/benchmark.h" |
13 | #include "test_macros.h" |
14 | |
15 | static const std::array<unsigned, 1000> input = [] { |
16 | std::mt19937 generator; |
17 | std::uniform_int_distribution<unsigned> distribution(0, std::numeric_limits<unsigned>::max()); |
18 | std::array<unsigned, 1000> result; |
19 | std::generate_n(result.begin(), result.size(), [&] { return distribution(generator); }); |
20 | return result; |
21 | }(); |
22 | |
23 | static void BM_to_chars_good(benchmark::State& state) { |
24 | char buffer[128]; |
25 | int base = state.range(pos: 0); |
26 | while (state.KeepRunningBatch(input.size())) |
27 | for (auto value : input) |
28 | benchmark::DoNotOptimize(std::to_chars(buffer, &buffer[128], value, base)); |
29 | } |
30 | BENCHMARK(BM_to_chars_good)->DenseRange(start: 2, limit: 36, step: 1); |
31 | |
32 | static void BM_to_chars_bad(benchmark::State& state) { |
33 | char buffer[128]; |
34 | int base = state.range(pos: 0); |
35 | struct sample { |
36 | unsigned size; |
37 | unsigned value; |
38 | }; |
39 | std::array<sample, 1000> data; |
40 | // Assume the failure occurs, on average, halfway during the conversion. |
41 | std::transform(input.begin(), input.end(), data.begin(), [&](unsigned value) { |
42 | std::to_chars_result result = std::to_chars(first: buffer, last: &buffer[128], value: value, base: base); |
43 | return sample{.size: unsigned((result.ptr - buffer) / 2), .value: value}; |
44 | }); |
45 | |
46 | while (state.KeepRunningBatch(n: data.size())) |
47 | for (auto element : data) |
48 | benchmark::DoNotOptimize(value: std::to_chars(first: buffer, last: &buffer[element.size], value: element.value, base: base)); |
49 | } |
50 | BENCHMARK(BM_to_chars_bad)->DenseRange(start: 2, limit: 36, step: 1); |
51 | |
52 | int main(int argc, char** argv) { |
53 | benchmark::Initialize(argc: &argc, argv); |
54 | if (benchmark::ReportUnrecognizedArguments(argc, argv)) |
55 | return 1; |
56 | |
57 | benchmark::RunSpecifiedBenchmarks(); |
58 | } |
59 | |