]>
git.proxmox.com Git - ceph.git/blob - ceph/src/boost/libs/compute/example/monte_carlo.cpp
1 //---------------------------------------------------------------------------//
2 // Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>
4 // Distributed under the Boost Software License, Version 1.0
5 // See accompanying file LICENSE_1_0.txt or copy at
6 // http://www.boost.org/LICENSE_1_0.txt
8 // See http://boostorg.github.com/compute for more information.
9 //---------------------------------------------------------------------------//
13 #include <boost/compute/function.hpp>
14 #include <boost/compute/system.hpp>
15 #include <boost/compute/algorithm/count_if.hpp>
16 #include <boost/compute/container/vector.hpp>
17 #include <boost/compute/iterator/buffer_iterator.hpp>
18 #include <boost/compute/random/default_random_engine.hpp>
19 #include <boost/compute/types/fundamental.hpp>
21 namespace compute
= boost::compute
;
25 // get default device and setup context
26 compute::device gpu
= compute::system::default_device();
27 compute::context
context(gpu
);
28 compute::command_queue
queue(context
, gpu
);
30 std::cout
<< "device: " << gpu
.name() << std::endl
;
33 using compute::uint2_
;
36 #ifdef CI_BUILD // lower number of points for CI builds
39 // ten million random points
43 // generate random numbers
44 compute::default_random_engine
rng(queue
);
45 compute::vector
<uint_
> vector(n
* 2, context
);
46 rng
.generate(vector
.begin(), vector
.end(), queue
);
48 // function returing true if the point is within the unit circle
49 BOOST_COMPUTE_FUNCTION(bool, is_in_unit_circle
, (const uint2_ point
),
51 const float x
= point
.x
/ (float) UINT_MAX
- 1;
52 const float y
= point
.y
/ (float) UINT_MAX
- 1;
54 return (x
*x
+ y
*y
) < 1.0f
;
57 // iterate over vector<uint> as vector<uint2>
58 compute::buffer_iterator
<uint2_
> start
=
59 compute::make_buffer_iterator
<uint2_
>(vector
.get_buffer(), 0);
60 compute::buffer_iterator
<uint2_
> end
=
61 compute::make_buffer_iterator
<uint2_
>(vector
.get_buffer(), vector
.size() / 2);
63 // count number of random points within the unit circle
64 size_t count
= compute::count_if(start
, end
, is_in_unit_circle
, queue
);
67 float count_f
= static_cast<float>(count
);
68 std::cout
<< "count: " << count
<< " / " << n
<< std::endl
;
69 std::cout
<< "ratio: " << count_f
/ float(n
) << std::endl
;
70 std::cout
<< "pi = " << (count_f
/ float(n
)) * 4.0f
<< std::endl
;