Imported Upstream version 1.72.0
[platform/upstream/boost.git] / libs / histogram / test / histogram_threaded_test.cpp
1 // Copyright 2019 Hans Dembinski
2 //
3 // Distributed under the Boost Software License, Version 1.0.
4 // (See accompanying file LICENSE_1_0.txt
5 // or copy at http://www.boost.org/LICENSE_1_0.txt)
6
7 #include <boost/core/lightweight_test.hpp>
8 #include <boost/histogram/accumulators/thread_safe.hpp>
9 #include <boost/histogram/algorithm/sum.hpp>
10 #include <boost/histogram/axis/integer.hpp>
11 #include <boost/histogram/axis/ostream.hpp>
12 #include <boost/histogram/ostream.hpp>
13 #include <boost/histogram/storage_adaptor.hpp>
14 #include <iostream>
15 #include <random>
16 #include <thread>
17 #include "throw_exception.hpp"
18 #include "utility_histogram.hpp"
19
20 using namespace boost::histogram;
21
22 constexpr auto n_fill = 80000;
23 static_assert(n_fill % 4 == 0, "must be multiple of 4");
24
25 template <class Tag, class A1, class A2, class X, class Y>
26 void fill_test(const A1& a1, const A2& a2, const X& x, const Y& y) {
27   auto h1 = make_s(Tag{}, dense_storage<int>(), a1, a2);
28   auto xy = {x, y};
29   h1.fill(xy);
30
31   auto h2 = make_s(Tag{}, dense_storage<accumulators::thread_safe<int>>(), a1, a2);
32   auto run = [&h2, &x, &y](int k) {
33     constexpr auto shift = n_fill / 4;
34     auto xit = x.cbegin() + k * shift;
35     auto yit = y.cbegin() + k * shift;
36     for (unsigned i = 0; i < shift; ++i) h2(*xit++, *yit++);
37   };
38
39   std::thread t1([&] { run(0); });
40   std::thread t2([&] { run(1); });
41   std::thread t3([&] { run(2); });
42   std::thread t4([&] { run(3); });
43   t1.join();
44   t2.join();
45   t3.join();
46   t4.join();
47
48   BOOST_TEST_EQ(algorithm::sum(h1), n_fill);
49   BOOST_TEST_EQ(algorithm::sum(h2), n_fill);
50   BOOST_TEST_EQ(h1, h2);
51 }
52
53 template <class T>
54 void tests() {
55   std::mt19937 gen(1);
56   std::uniform_int_distribution<> id(-5, 5);
57   std::vector<int> vi(n_fill), vj(n_fill);
58   std::generate(vi.begin(), vi.end(), [&] { return id(gen); });
59   std::generate(vj.begin(), vj.end(), [&] { return id(gen); });
60
61   using i = axis::integer<>;
62   using ig = axis::integer<int, use_default, axis::option::growth_t>;
63   fill_test<T>(i{0, 1}, i{0, 1}, vi, vj);
64   fill_test<T>(ig{0, 1}, i{0, 1}, vi, vj);
65   fill_test<T>(i{0, 1}, ig{0, 1}, vi, vj);
66   fill_test<T>(ig{0, 1}, ig{0, 1}, vi, vj);
67 }
68
69 int main() {
70   tests<static_tag>();
71   tests<dynamic_tag>();
72
73   return boost::report_errors();
74 }