2 * Copyright 2017 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.
22 #include <glog/logging.h>
24 #include <folly/gen/Base.h>
25 #include <folly/gen/Parallel.h>
26 #include <folly/portability/GTest.h>
28 using namespace folly;
29 using namespace folly::gen;
32 const auto square = [](int i) { return i * i; };
33 const auto even = [](int i) { return 0 == i % 2; };
34 static auto sleepyWork = [](int i) {
35 const auto sleepyTime = std::chrono::microseconds(100);
36 std::this_thread::sleep_for(sleepyTime);
40 static auto isPrime = [](int n) {
44 for (int d = 3; d * d <= n; d += 2) {
55 std::unique_ptr<T> operator()(T t) const {
56 return std::make_unique<T>(std::move(t));
60 static auto primes = seq(1, 1 << 14)
62 | as<vector<size_t>>();
64 static auto primeFactors = [](int n) {
66 | filter([&](int d) { return 0 == n % d; })
70 TEST(ParallelTest, Serial) {
72 seq(1,10) | map(square) | filter(even) | sum,
73 seq(1,10) | parallel(map(square) | filter(even)) | sum);
76 auto heavyWork = map(primeFactors);
78 TEST(ParallelTest, ComputeBound64) {
80 EXPECT_EQ(seq<size_t>(1, length) | heavyWork | sum,
81 seq<size_t>(1, length) | parallel(heavyWork) | sum);
84 TEST(ParallelTest, Take) {
87 EXPECT_EQ(seq(1, length) | take(limit) | count,
88 seq(1, length) | parallel(heavyWork) | take(limit) | count);
92 TEST(ParallelTest, Unique) {
93 auto uniqued = from(primes) | map(makeUnique) | as<vector>();
94 EXPECT_EQ(primes.size(),
95 from(primes) | parallel(map(makeUnique)) |
96 parallel(dereference | map(makeUnique)) | dereference | count);
98 from(primes) | parallel(map(makeUnique)) |
99 parallel(dereference | map(makeUnique)) | dereference |
103 TEST(ParallelTest, PSum) {
104 EXPECT_EQ(from(primes) | map(sleepyWork) | sum,
105 from(primes) | parallel(map(sleepyWork) | sub(sum)) | sum);
108 int main(int argc, char *argv[]) {
109 testing::InitGoogleTest(&argc, argv);
110 gflags::ParseCommandLineFlags(&argc, &argv, true);
111 return RUN_ALL_TESTS();