serial_accumulate.hpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //---------------------------------------------------------------------------//
  2. // Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>
  3. //
  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
  7. //
  8. // See http://boostorg.github.com/compute for more information.
  9. //---------------------------------------------------------------------------//
  10. #ifndef BOOST_COMPUTE_ALGORITHM_DETAIL_SERIAL_ACCUMULATE_HPP
  11. #define BOOST_COMPUTE_ALGORITHM_DETAIL_SERIAL_ACCUMULATE_HPP
  12. #include <boost/compute/command_queue.hpp>
  13. #include <boost/compute/detail/meta_kernel.hpp>
  14. #include <boost/compute/detail/iterator_range_size.hpp>
  15. namespace boost {
  16. namespace compute {
  17. namespace detail {
  18. template<class InputIterator, class OutputIterator, class T, class BinaryFunction>
  19. inline void serial_accumulate(InputIterator first,
  20. InputIterator last,
  21. OutputIterator result,
  22. T init,
  23. BinaryFunction function,
  24. command_queue &queue)
  25. {
  26. const context &context = queue.get_context();
  27. size_t count = detail::iterator_range_size(first, last);
  28. meta_kernel k("serial_accumulate");
  29. size_t init_arg = k.add_arg<T>("init");
  30. size_t count_arg = k.add_arg<cl_uint>("count");
  31. k <<
  32. k.decl<T>("result") << " = init;\n" <<
  33. "for(uint i = 0; i < count; i++)\n" <<
  34. " result = " << function(k.var<T>("result"),
  35. first[k.var<cl_uint>("i")]) << ";\n" <<
  36. result[0] << " = result;\n";
  37. kernel kernel = k.compile(context);
  38. kernel.set_arg(init_arg, init);
  39. kernel.set_arg(count_arg, static_cast<cl_uint>(count));
  40. queue.enqueue_task(kernel);
  41. }
  42. } // end detail namespace
  43. } // end compute namespace
  44. } // end boost namespace
  45. #endif // BOOST_COMPUTE_ALGORITHM_DETAIL_SERIAL_ACCUMULATE_HPP