Imported Upstream version 1.64.0
[platform/upstream/boost.git] / libs / fiber / performance / fiber / skynet_detach.cpp
1
2 //          Copyright Oliver Kowalke 2015.
3 // Distributed under the Boost Software License, Version 1.0.
4 //    (See accompanying file LICENSE_1_0.txt or copy at
5 //          http://www.boost.org/LICENSE_1_0.txt)
6
7 // based on https://github.com/atemerev/skynet from Alexander Temerev 
8
9 #include <algorithm>
10 #include <cassert>
11 #include <chrono>
12 #include <cstddef>
13 #include <cstdint>
14 #include <cstdlib>
15 #include <iostream>
16 #include <memory>
17 #include <numeric>
18 #include <vector>
19
20 #include <boost/fiber/all.hpp>
21
22 using allocator_type = boost::fibers::fixedsize_stack;
23 using channel_type = boost::fibers::buffered_channel< std::uint64_t >;
24 using clock_type = std::chrono::steady_clock;
25 using duration_type = clock_type::duration;
26 using time_point_type = clock_type::time_point;
27
28 // microbenchmark
29 void skynet( allocator_type & salloc, channel_type & c, std::size_t num, std::size_t size, std::size_t div) {
30     if ( 1 == size) {
31         c.push( num);
32     } else {
33         channel_type rc{ 16 };
34         for ( std::size_t i = 0; i < div; ++i) {
35             auto sub_num = num + i * size / div;
36             boost::fibers::fiber{ boost::fibers::launch::dispatch,
37                               std::allocator_arg, salloc,
38                               skynet,
39                               std::ref( salloc), std::ref( rc), sub_num, size / div, div }.detach();
40         }
41         std::uint64_t sum{ 0 };
42         for ( std::size_t i = 0; i < div; ++i) {
43             sum += rc.value_pop();
44         }
45         c.push( sum);
46     }
47 }
48
49 int main() {
50     try {
51         std::size_t size{ 1000000 };
52         std::size_t div{ 10 };
53         allocator_type salloc{ allocator_type::traits_type::page_size() };
54         std::uint64_t result{ 0 };
55         duration_type duration{ duration_type::zero() };
56         channel_type rc{ 2 };
57         time_point_type start{ clock_type::now() };
58         skynet( salloc, rc, 0, size, div);
59         result = rc.value_pop();
60         duration = clock_type::now() - start;
61         std::cout << "Result: " << result << " in " << duration.count() / 1000000 << " ms" << std::endl;
62         std::cout << "done." << std::endl;
63         return EXIT_SUCCESS;
64     } catch ( std::exception const& e) {
65         std::cerr << "exception: " << e.what() << std::endl;
66     } catch (...) {
67         std::cerr << "unhandled exception" << std::endl;
68     }
69         return EXIT_FAILURE;
70 }