Copyright 2014->2015
[folly.git] / folly / gen / test / FileBenchmark.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 #include <thread>
17 #include <glog/logging.h>
18
19 #include <folly/Benchmark.h>
20 #include <folly/File.h>
21 #include <folly/gen/Base.h>
22 #include <folly/gen/File.h>
23
24 using namespace folly::gen;
25
26 BENCHMARK(ByLine_Pipes, iters) {
27   std::thread thread;
28   int rfd = -1;
29   int wfd;
30   BENCHMARK_SUSPEND {
31     int p[2];
32     CHECK_ERR(::pipe(p));
33     rfd = p[0];
34     wfd = p[1];
35     thread = std::thread([wfd, iters] {
36       char x = 'x';
37       PCHECK(::write(wfd, &x, 1) == 1);  // signal startup
38       FILE* f = fdopen(wfd, "w");
39       PCHECK(f);
40       for (size_t i = 1; i <= iters; ++i) {
41         fprintf(f, "%zu\n", i);
42       }
43       fclose(f);
44     });
45     char buf;
46     PCHECK(::read(rfd, &buf, 1) == 1);  // wait for startup
47   }
48
49   CHECK_ERR(rfd);
50   auto s = byLine(folly::File(rfd)) | eachTo<int64_t>() | sum;
51   folly::doNotOptimizeAway(s);
52
53   BENCHMARK_SUSPEND {
54     ::close(rfd);
55     CHECK_EQ(s, int64_t(iters) * (iters + 1) / 2);
56     thread.join();
57   }
58 }
59
60 // Results from an Intel(R) Xeon(R) CPU E5-2660 0 @ 2.20GHz
61 // ============================================================================
62 // folly/gen/test/FileBenchmark.cpp                relative  time/iter  iters/s
63 // ============================================================================
64 // ByLine_Pipes                                               148.63ns    6.73M
65 // ============================================================================
66
67 int main(int argc, char *argv[]) {
68   gflags::ParseCommandLineFlags(&argc, &argv, true);
69   folly::runBenchmarks();
70   return 0;
71 }