1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "android-base/format.h"
18 
19 #include <limits>
20 
21 #include <benchmark/benchmark.h>
22 
23 #include "android-base/stringprintf.h"
24 
25 using android::base::StringPrintf;
26 
BenchmarkFormatInt(benchmark::State & state)27 static void BenchmarkFormatInt(benchmark::State& state) {
28   for (auto _ : state) {
29     benchmark::DoNotOptimize(fmt::format("{} {} {}", 42, std::numeric_limits<int>::min(),
30                                          std::numeric_limits<int>::max()));
31   }
32 }
33 
34 BENCHMARK(BenchmarkFormatInt);
35 
BenchmarkStringPrintfInt(benchmark::State & state)36 static void BenchmarkStringPrintfInt(benchmark::State& state) {
37   for (auto _ : state) {
38     benchmark::DoNotOptimize(StringPrintf("%d %d %d", 42, std::numeric_limits<int>::min(),
39                                           std::numeric_limits<int>::max()));
40   }
41 }
42 
43 BENCHMARK(BenchmarkStringPrintfInt);
44 
BenchmarkFormatFloat(benchmark::State & state)45 static void BenchmarkFormatFloat(benchmark::State& state) {
46   for (auto _ : state) {
47     benchmark::DoNotOptimize(fmt::format("{} {} {}", 42.42, std::numeric_limits<float>::min(),
48                                          std::numeric_limits<float>::max()));
49   }
50 }
51 
52 BENCHMARK(BenchmarkFormatFloat);
53 
BenchmarkStringPrintfFloat(benchmark::State & state)54 static void BenchmarkStringPrintfFloat(benchmark::State& state) {
55   for (auto _ : state) {
56     benchmark::DoNotOptimize(StringPrintf("%f %f %f", 42.42, std::numeric_limits<float>::min(),
57                                           std::numeric_limits<float>::max()));
58   }
59 }
60 
61 BENCHMARK(BenchmarkStringPrintfFloat);
62 
BenchmarkFormatStrings(benchmark::State & state)63 static void BenchmarkFormatStrings(benchmark::State& state) {
64   for (auto _ : state) {
65     benchmark::DoNotOptimize(fmt::format("{} hello there {}", "hi,", "!!"));
66   }
67 }
68 
69 BENCHMARK(BenchmarkFormatStrings);
70 
BenchmarkStringPrintfStrings(benchmark::State & state)71 static void BenchmarkStringPrintfStrings(benchmark::State& state) {
72   for (auto _ : state) {
73     benchmark::DoNotOptimize(StringPrintf("%s hello there %s", "hi,", "!!"));
74   }
75 }
76 
77 BENCHMARK(BenchmarkStringPrintfStrings);
78 
79 // Run the benchmark
80 BENCHMARK_MAIN();
81