summaryrefslogtreecommitdiff
path: root/Rx/v2/test/operators/group_by.cpp
blob: 1d85193a83c795279cc670952e82d28a27adcd17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#include "rxcpp/rx.hpp"
namespace rxu=rxcpp::util;
namespace rxs=rxcpp::sources;
namespace rxsc=rxcpp::schedulers;

#include "rxcpp/rx-test.hpp"
#include "catch.hpp"

#include <locale>

SCENARIO("range partitioned by group_by across hardware threads to derive pi", "[hide][pi][group_by][observe_on][long][perf]"){
    GIVEN("a for loop"){
        WHEN("partitioning pi series across all hardware threads"){

            std::atomic_int c;
            c = 0;
            auto pi = [&](int k) {
                ++c;
                return ( k % 2 == 0 ? -4.0L : 4.0L ) / ( ( 2.0L * k ) - 1.0L );
            };

            using namespace std::chrono;
            auto start = steady_clock::now();

            // share an output thread across all the producer threads
            auto outputthread = rxcpp::observe_on_one_worker(rxcpp::observe_on_new_thread().create_coordinator().get_scheduler());

            // use all available hardware threads
            auto total = rxcpp::observable<>::range(0, 19).
                group_by(
                    [](int i) -> int {return i % std::thread::hardware_concurrency();},
                    [](int i){return i;}).
                map(
                    [=, &c](rxcpp::grouped_observable<int, int> onproc) {
                        auto key = onproc.get_key();
                        // share a producer thread across all the ranges in this group
                        auto producerthread = rxcpp::observe_on_one_worker(rxcpp::observe_on_new_thread().create_coordinator().get_scheduler());
                        return onproc.
                            map(
                                [=, &c](int index){
                                    static const int chunk = 1000000;
                                    auto first = (chunk * index) + 1;
                                    auto last =   chunk * (index + 1);
                                    std::cout << std::setw(3) << index << ": range - " << first << "-" << last << std::endl;

                                    return rxcpp::observable<>::range(first, last, producerthread).
                                        map(pi).
                                        sum(). // each thread maps and reduces its contribution to the answer
                                        map(
                                            [=](long double v){
                                                std::stringstream message;
                                                message << key << " on " << std::this_thread::get_id() << " - value: " << std::setprecision(16) << v;
                                                return std::make_tuple(message.str(), v);
                                            }).
                                        as_dynamic();
                                }).
                            concat(). // only subscribe to one range at a time in this group.
                            observe_on(outputthread).
                            map(rxcpp::util::apply_to(
                                [](std::string message, long double v){
                                    std::cout << message << std::endl;
                                    return v;
                                })).
                            as_dynamic();
                    }).
                merge().
                sum(). // reduces the contributions from all the threads to the answer
                as_blocking().
                last();

            std::cout << std::setprecision(16) << "Pi: " << total << std::endl;
            auto finish = steady_clock::now();
            auto msElapsed = duration_cast<milliseconds>(finish-start);
            std::cout << "pi using group_by and concat to partition the work : " << c << " calls to pi(), " << msElapsed.count() << "ms elapsed, " << c / (msElapsed.count() / 1000.0) << " ops/sec" << std::endl;

        }
    }
}

SCENARIO("range partitioned by dividing work across hardware threads to derive pi", "[hide][pi][observe_on][long][perf]"){
    GIVEN("a for loop"){
        WHEN("partitioning pi series across all hardware threads"){

            std::atomic_int c;
            c = 0;
            auto pi = [&](int k) {
                ++c;
                return ( k % 2 == 0 ? -4.0L : 4.0L ) / ( ( 2.0L * k ) - 1.0L );
            };

            using namespace std::chrono;
            auto start = steady_clock::now();

            // share an output thread across all the producer threads
            auto outputthread = rxcpp::observe_on_one_worker(rxcpp::observe_on_new_thread().create_coordinator().get_scheduler());

            // use all available hardware threads
            auto total = rxcpp::observable<>::range(0, std::thread::hardware_concurrency() - 1).
                map(
                    [=, &c](int index){
                        // partition equally across threads
                        static const int chunk = 20000000 / std::thread::hardware_concurrency();
                        auto first = (chunk * index) + 1;
                        auto last =   chunk * (index + 1);
                        std::cout << std::setw(3) << index << ": range - " << first << "-" << last << std::endl;

                        return rxcpp::observable<>::range(first, last, rxcpp::observe_on_new_thread()).
                            map(pi).
                            sum(). // each thread maps and reduces its contribution to the answer
                            map(
                                [=](long double v){
                                    std::stringstream message;
                                    message << std::this_thread::get_id() << " - value: " << std::setprecision(16) << v;
                                    return std::make_tuple(message.str(), v);
                                }).
                            as_dynamic();
                    }).
                observe_on(outputthread).
                merge().
                map(rxcpp::util::apply_to(
                    [](std::string message, long double v){
                        std::cout << message << std::endl;
                        return v;
                    })).
                sum(). // reduces the contributions from all the threads to the answer
                as_blocking().
                last();

            std::cout << std::setprecision(16) << "Pi: " << total << std::endl;
            auto finish = steady_clock::now();
            auto msElapsed = duration_cast<milliseconds>(finish-start);
            std::cout << "pi using division of the whole range to partition the work : " << c << " calls to pi(), " << msElapsed.count() << "ms elapsed, " << c / (msElapsed.count() / 1000.0) << " ops/sec" << std::endl;

        }
    }
}

char whitespace(char c) {
    return std::isspace<char>(c, std::locale::classic());
}

std::string trim(std::string s) {
    auto first = std::find_if_not(s.begin(), s.end(), whitespace);
    auto last = std::find_if_not(s.rbegin(), s.rend(), whitespace);
    if (last != s.rend()) {
        s.erase(s.end() - (last-s.rbegin()), s.end());
    }
    s.erase(s.begin(), first);
    return std::move(s);
}

bool tolowerLess(char lhs, char rhs) {
    return std::tolower(lhs, std::locale::classic()) < std::tolower(rhs, std::locale::classic());
}

bool tolowerStringLess(const std::string& lhs, const std::string& rhs) {
    return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end(), tolowerLess);
}

SCENARIO("group_by", "[group_by][operators]"){
    GIVEN("1 hot observable of ints."){
        auto sc = rxsc::make_test();
        auto w = sc.create_worker();
        const rxsc::test::messages<std::string> on;
        int keyInvoked = 0;
        int marbleInvoked = 0;

        auto xs = sc.make_hot_observable({
            on.on_next(90, "error"),
            on.on_next(110, "error"),
            on.on_next(130, "error"),
            on.on_next(220, "  foo"),
            on.on_next(240, " FoO "),
            on.on_next(270, "baR  "),
            on.on_next(310, "foO "),
            on.on_next(350, " Baz   "),
            on.on_next(360, "  qux "),
            on.on_next(390, "   bar"),
            on.on_next(420, " BAR  "),
            on.on_next(470, "FOO "),
            on.on_next(480, "baz  "),
            on.on_next(510, " bAZ "),
            on.on_next(530, "    fOo    "),
            on.on_completed(570),
            on.on_next(580, "error"),
            on.on_completed(600),
            on.on_error(650, new std::runtime_error("error in completed sequence"))
        });

        WHEN("group each int with the next 2 ints"){

            auto res = w.start(
                [&]() {
                    return xs
                        .group_by(
                            [&](std::string v){
                                ++keyInvoked;
                                return trim(std::move(v));
                            },
                            [&](std::string v){
                                ++marbleInvoked;
                                std::reverse(v.begin(), v.end());
                                return v;
                            },
                            tolowerStringLess)
                        .map([](const rxcpp::grouped_observable<std::string, std::string>& g){return g.get_key();})
                        // forget type to workaround lambda deduction bug on msvc 2013
                        .as_dynamic();
                }
            );

            THEN("the output contains groups of ints"){
                auto required = rxu::to_vector({
                    on.on_next(220, "foo"),
                    on.on_next(270, "baR"),
                    on.on_next(350, "Baz"),
                    on.on_next(360, "qux"),
                    on.on_completed(570)
                });
                auto actual = res.get_observer().messages();
                REQUIRE(required == actual);
            }

            THEN("there was one subscription and one unsubscription to the xs"){
                auto required = rxu::to_vector({
                    on.subscribe(200, 570)
                });
                auto actual = xs.subscriptions();
                REQUIRE(required == actual);
            }

            THEN("key selector was invoked for each value"){
                REQUIRE(12 == keyInvoked);
            }

            THEN("marble selector was invoked for each value"){
                REQUIRE(12 == marbleInvoked);
            }
        }
    }
}