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 <format>
12
13#include <string>
14
15#include "benchmark/benchmark.h"
16#include "make_string.h"
17#include "test_macros.h"
18
19#define CSTR(S) MAKE_CSTRING(CharT, S)
20
21template <class CharT>
22static void BM_format_string(benchmark::State& state) {
23 size_t size = state.range(pos: 0);
24 std::basic_string<CharT> str(size, CharT('*'));
25
26 while (state.KeepRunningBatch(n: str.size())) {
27 std::basic_string<CharT> s = std::format(CSTR("{}"), str);
28 benchmark::DoNotOptimize(s);
29 }
30
31 state.SetBytesProcessed(state.iterations() * size * sizeof(CharT));
32}
33BENCHMARK(BM_format_string<char>)->RangeMultiplier(multiplier: 2)->Range(start: 1, limit: 1 << 20);
34#ifndef TEST_HAS_NO_WIDE_CHARACTERS
35BENCHMARK(BM_format_string<wchar_t>)->RangeMultiplier(multiplier: 2)->Range(start: 1, limit: 1 << 20);
36#endif
37
38template <class CharT>
39static void BM_string_without_formatting(benchmark::State& state) {
40 for (auto _ : state) {
41 benchmark::DoNotOptimize(std::format(CSTR("Hello, World!")));
42 }
43}
44BENCHMARK(BM_string_without_formatting<char>);
45#ifndef TEST_HAS_NO_WIDE_CHARACTERS
46BENCHMARK(BM_string_without_formatting<wchar_t>);
47#endif
48
49BENCHMARK_MAIN();
50

source code of libcxx/test/benchmarks/format/format.bench.cpp