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