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 //---------------------------------------------------------------------------//
11 #ifndef BOOST_COMPUTE_ALGORITHM_DETAIL_SERIAL_REDUCE_HPP
12 #define BOOST_COMPUTE_ALGORITHM_DETAIL_SERIAL_REDUCE_HPP
14 #include <boost/compute/command_queue.hpp>
15 #include <boost/compute/detail/meta_kernel.hpp>
16 #include <boost/compute/detail/iterator_range_size.hpp>
17 #include <boost/compute/type_traits/result_of.hpp>
23 // Space complexity: O(1)
24 template<class InputIterator, class OutputIterator, class BinaryFunction>
25 inline void serial_reduce(InputIterator first,
27 OutputIterator result,
28 BinaryFunction function,
32 std::iterator_traits<InputIterator>::value_type T;
34 ::boost::compute::result_of<BinaryFunction(T, T)>::type result_type;
36 const context &context = queue.get_context();
37 size_t count = detail::iterator_range_size(first, last);
42 meta_kernel k("serial_reduce");
43 size_t count_arg = k.add_arg<cl_uint>("count");
46 k.decl<result_type>("result") << " = " << first[0] << ";\n" <<
47 "for(uint i = 1; i < count; i++)\n" <<
48 " result = " << function(k.var<T>("result"),
49 first[k.var<uint_>("i")]) << ";\n" <<
50 result[0] << " = result;\n";
52 kernel kernel = k.compile(context);
54 kernel.set_arg(count_arg, static_cast<uint_>(count));
56 queue.enqueue_task(kernel);
59 } // end detail namespace
60 } // end compute namespace
61 } // end boost namespace
63 #endif // BOOST_COMPUTE_ALGORITHM_DETAIL_SERIAL_REDUCE_HPP