20 #include "benchmark/benchmark.h" 25 const char kStringOne[] =
"Once Upon A Time, ";
26 const char kStringTwo[] =
"There was a std::string benchmark";
30 inline int IncrementAlternatingSign(
int i) {
31 return i > 0 ? -i : 1 -
i;
34 void BM_Sum_By_StrCat(benchmark::State& state) {
37 for (
auto _ : state) {
39 strcpy(foo,
absl::StrCat(kStringOne, i, kStringTwo, i * 65536ULL).c_str());
41 for (
char* f = &foo[0]; *f != 0; ++f) {
44 benchmark::DoNotOptimize(sum);
45 i = IncrementAlternatingSign(i);
48 BENCHMARK(BM_Sum_By_StrCat);
50 void BM_StrCat_By_snprintf(benchmark::State& state) {
53 for (
auto _ : state) {
54 snprintf(on_stack,
sizeof(on_stack),
"%s %s:%d", kStringOne, kStringTwo, i);
55 i = IncrementAlternatingSign(i);
58 BENCHMARK(BM_StrCat_By_snprintf);
60 void BM_StrCat_By_Strings(benchmark::State& state) {
62 for (
auto _ : state) {
64 std::string(kStringOne) +
" " + kStringTwo +
":" +
absl::StrCat(i);
65 benchmark::DoNotOptimize(result);
66 i = IncrementAlternatingSign(i);
69 BENCHMARK(BM_StrCat_By_Strings);
71 void BM_StrCat_By_StringOpPlus(benchmark::State& state) {
73 for (
auto _ : state) {
74 std::string result = kStringOne;
79 benchmark::DoNotOptimize(result);
80 i = IncrementAlternatingSign(i);
83 BENCHMARK(BM_StrCat_By_StringOpPlus);
85 void BM_StrCat_By_StrCat(benchmark::State& state) {
87 for (
auto _ : state) {
88 std::string result =
absl::StrCat(kStringOne,
" ", kStringTwo,
":", i);
89 benchmark::DoNotOptimize(result);
90 i = IncrementAlternatingSign(i);
93 BENCHMARK(BM_StrCat_By_StrCat);
95 void BM_HexCat_By_StrCat(benchmark::State& state) {
97 for (
auto _ : state) {
100 benchmark::DoNotOptimize(result);
101 i = IncrementAlternatingSign(i);
104 BENCHMARK(BM_HexCat_By_StrCat);
106 void BM_HexCat_By_Substitute(benchmark::State& state) {
108 for (
auto _ : state) {
110 "$0 $1", kStringOne, reinterpret_cast<void*>(int64_t{i} + 0x10000000));
111 benchmark::DoNotOptimize(result);
112 i = IncrementAlternatingSign(i);
115 BENCHMARK(BM_HexCat_By_Substitute);
117 void BM_FloatToString_By_StrCat(benchmark::State& state) {
120 for (
auto _ : state) {
121 std::string result =
absl::StrCat(foo += 1.001f,
" != ", int64_t{i});
122 benchmark::DoNotOptimize(result);
123 i = IncrementAlternatingSign(i);
126 BENCHMARK(BM_FloatToString_By_StrCat);
128 void BM_DoubleToString_By_SixDigits(benchmark::State& state) {
131 for (
auto _ : state) {
134 benchmark::DoNotOptimize(result);
135 i = IncrementAlternatingSign(i);
138 BENCHMARK(BM_DoubleToString_By_SixDigits);
std::string StrCat(const AlphaNum &a, const AlphaNum &b)
strings_internal::AlphaNumBuffer< numbers_internal::kSixDigitsToBufferSize > SixDigits(double d)
ABSL_MUST_USE_RESULT std::string Substitute(absl::string_view format)