2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
23 #include <folly/Benchmark.h>
24 #include <folly/gen/Base.h>
25 #include <folly/gen/ParallelMap.h>
27 using namespace folly::gen;
30 std::max(1, (int32_t) sysconf(_SC_NPROCESSORS_CONF) / 2),
33 constexpr int kFib = 35; // unit of work
34 size_t fib(int n) { return n <= 1 ? 1 : fib(n-1) * fib(n-2); }
36 BENCHMARK(FibSumMap, n) {
39 | map([](int) { return fib(kFib); })
41 folly::doNotOptimizeAway(result);
44 BENCHMARK_RELATIVE(FibSumPmap, n) {
45 // Schedule more work: enough so that each worker thread does the
46 // same amount as one FibSumMap.
47 const size_t kNumThreads = FLAGS_threads;
49 seq(1, (int) (n * kNumThreads))
50 | pmap([](int) { return fib(kFib); }, kNumThreads)
52 folly::doNotOptimizeAway(result);
55 BENCHMARK_RELATIVE(FibSumThreads, n) {
56 // Schedule kNumThreads to execute the same code as FibSumMap.
57 const size_t kNumThreads = FLAGS_threads;
58 std::vector<std::thread> workers;
59 workers.reserve(kNumThreads);
63 | map([](int) { return fib(kFib); })
65 folly::doNotOptimizeAway(result);
67 for (size_t i = 0; i < kNumThreads; i++) {
68 workers.push_back(std::thread(fn));
70 for (auto& w : workers) { w.join(); }
74 ============================================================================
75 folly/gen/test/ParallelMapBenchmark.cpp relative time/iter iters/s
76 ============================================================================
77 FibSumMap 41.64ms 24.02
78 FibSumPmap 98.38% 42.32ms 23.63
79 FibSumThreads 94.48% 44.07ms 22.69
80 ============================================================================
87 int main(int argc, char *argv[]) {
88 gflags::ParseCommandLineFlags(&argc, &argv, true);
89 folly::runBenchmarks();