339fd293ad30aa9993a017e5d38d9e54c355f6b8
[folly.git] / folly / gen / test / FileBenchmark.cpp
1 /*
2  * Copyright 2014 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;
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 (int i = 1; i <= iters; ++i) {
41         fprintf(f, "%d\n", i);
42       }
43       fclose(f);
44     });
45     char buf;
46     PCHECK(::read(rfd, &buf, 1) == 1);  // wait for startup
47   }
48
49   auto s = byLine(folly::File(rfd)) | eachTo<int64_t>() | sum;
50   folly::doNotOptimizeAway(s);
51
52   BENCHMARK_SUSPEND {
53     ::close(rfd);
54     CHECK_EQ(s, int64_t(iters) * (iters + 1) / 2);
55     thread.join();
56   }
57 }
58
59 // Results from an Intel(R) Xeon(R) CPU E5-2660 0 @ 2.20GHz
60 // ============================================================================
61 // folly/gen/test/FileBenchmark.cpp                relative  time/iter  iters/s
62 // ============================================================================
63 // ByLine_Pipes                                               148.63ns    6.73M
64 // ============================================================================
65
66 int main(int argc, char *argv[]) {
67   google::ParseCommandLineFlags(&argc, &argv, true);
68   folly::runBenchmarks();
69   return 0;
70 }