1 //===- FormatVariadicBM.cpp - formatv() benchmark ---------- --------------===// 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 #include "benchmark/benchmark.h" 10 #include "llvm/Support/FormatVariadic.h" 11 #include <algorithm> 12 #include <string> 13 #include <vector> 14 15 using namespace llvm; 16 using namespace std; 17 18 // Generate a list of format strings that have `NumReplacements` replacements 19 // by permuting the replacements and some literal text. 20 static vector<string> getFormatStrings(int NumReplacements) { 21 vector<string> Components; 22 for (int I = 0; I < NumReplacements; I++) 23 Components.push_back("{" + to_string(I) + "}"); 24 // Intersperse these with some other literal text (_). 25 const string_view Literal = "____"; 26 for (char C : Literal) 27 Components.push_back(string(1, C)); 28 29 vector<string> Formats; 30 do { 31 string Concat; 32 for (const string &C : Components) 33 Concat += C; 34 Formats.emplace_back(Concat); 35 } while (next_permutation(Components.begin(), Components.end())); 36 return Formats; 37 } 38 39 // Generate the set of formats to exercise outside the benchmark code. 40 static const vector<vector<string>> Formats = { 41 getFormatStrings(1), getFormatStrings(2), getFormatStrings(3), 42 getFormatStrings(4), getFormatStrings(5), 43 }; 44 45 // Benchmark formatv() for a variety of format strings and 1-5 replacements. 46 static void BM_FormatVariadic(benchmark::State &state) { 47 for (auto _ : state) { 48 for (const string &Fmt : Formats[0]) 49 formatv(Fmt.c_str(), 1).str(); 50 for (const string &Fmt : Formats[1]) 51 formatv(Fmt.c_str(), 1, 2).str(); 52 for (const string &Fmt : Formats[2]) 53 formatv(Fmt.c_str(), 1, 2, 3).str(); 54 for (const string &Fmt : Formats[3]) 55 formatv(Fmt.c_str(), 1, 2, 3, 4).str(); 56 for (const string &Fmt : Formats[4]) 57 formatv(Fmt.c_str(), 1, 2, 3, 4, 5).str(); 58 } 59 } 60 61 BENCHMARK(BM_FormatVariadic); 62 63 BENCHMARK_MAIN(); 64