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
15static 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
23static void BM_to_chars_good(benchmark::State& state) {
24 char buffer[128];
25 int base = state.range(0);
26 while (state.KeepRunningBatch(input.size()))
27 for (auto value : input)
28 benchmark::DoNotOptimize(std::to_chars(buffer, &buffer[128], value, base));
29}
30BENCHMARK(BM_to_chars_good)->DenseRange(2, 36, 1);
31
32static void BM_to_chars_bad(benchmark::State& state) {
33 char buffer[128];
34 int base = state.range(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(buffer, &buffer[128], value, base);
43 return sample{unsigned((result.ptr - buffer) / 2), value};
44 });
45
46 while (state.KeepRunningBatch(data.size()))
47 for (auto element : data)
48 benchmark::DoNotOptimize(std::to_chars(buffer, &buffer[element.size], element.value, base));
49}
50BENCHMARK(BM_to_chars_bad)->DenseRange(2, 36, 1);
51
52int main(int argc, char** argv) {
53 benchmark::Initialize(&argc, argv);
54 if (benchmark::ReportUnrecognizedArguments(argc, argv))
55 return 1;
56
57 benchmark::RunSpecifiedBenchmarks();
58}
59