c9c90d7dbee70892074359764e52dcf58d25f12f
[folly.git] / folly / test / StringBenchmark.cpp
1 /*
2  * Copyright 2015 Facebook, Inc.
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 <folly/Benchmark.h>
18 #include <folly/String.h>
19
20 BENCHMARK(libc_tolower, iters) {
21   static const size_t kSize = 256;
22   // This array is static to keep the compiler from optimizing the
23   // entire function down to a no-op if it has an inlined impl of
24   // tolower and thus is able to tell that there are no side-effects.
25   // No side-effects + no writes to anything other than local variables
26   // + no return value = no need to run any of the code in the function.
27   // gcc, for example, makes that optimization with -O2.
28   static char input[kSize];
29   for (size_t i = 0; i < kSize; i++) {
30     input[i] = (char)(i & 0xff);
31   }
32   for (auto i = iters; i > 0; i--) {
33     for (size_t offset = 0; offset < kSize; offset++) {
34       input[offset] = tolower(input[offset]);
35     }
36   }
37 }
38
39 BENCHMARK(folly_toLowerAscii, iters) {
40   static const size_t kSize = 256;
41   static char input[kSize];
42   for (size_t i = 0; i < kSize; i++) {
43     input[i] = (char)(i & 0xff);
44   }
45   for (auto i = iters; i > 0; i--) {
46     folly::toLowerAscii(input, kSize);
47   }
48 }
49
50 int main(int argc, char** argv) {
51   gflags::ParseCommandLineFlags(&argc, &argv, true);
52   folly::runBenchmarks();
53   if (FLAGS_benchmark) {
54     folly::runBenchmarks();
55   }
56   return 0;
57 }
58
59 /*
60 Results on x86_64:
61 ============================================================================
62 folly/test/StringBenchmark.cpp                  relative  time/iter  iters/s
63 ============================================================================
64 libc_tolower                                                 1.30us  767.50K
65 folly_toLowerAscii                                         115.21ns    8.68M
66 ============================================================================
67 */