for_each.hpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //---------------------------------------------------------------------------//
  2. // Copyright (c) 2013 Kyle Lutz <[email protected]>
  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_FOR_EACH_HPP
  11. #define BOOST_COMPUTE_ALGORITHM_FOR_EACH_HPP
  12. #include <boost/static_assert.hpp>
  13. #include <boost/compute/system.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/is_device_iterator.hpp>
  18. namespace boost {
  19. namespace compute {
  20. namespace detail {
  21. template<class InputIterator, class Function>
  22. struct for_each_kernel : public meta_kernel
  23. {
  24. for_each_kernel(InputIterator first, InputIterator last, Function function)
  25. : meta_kernel("for_each")
  26. {
  27. // store range size
  28. m_count = detail::iterator_range_size(first, last);
  29. // setup kernel source
  30. *this << function(first[get_global_id(0)]) << ";\n";
  31. }
  32. void exec(command_queue &queue)
  33. {
  34. exec_1d(queue, 0, m_count);
  35. }
  36. size_t m_count;
  37. };
  38. } // end detail namespace
  39. /// Calls \p function on each element in the range [\p first, \p last).
  40. ///
  41. /// Space complexity: \Omega(1)
  42. ///
  43. /// \see transform()
  44. template<class InputIterator, class UnaryFunction>
  45. inline UnaryFunction for_each(InputIterator first,
  46. InputIterator last,
  47. UnaryFunction function,
  48. command_queue &queue = system::default_queue())
  49. {
  50. BOOST_STATIC_ASSERT(is_device_iterator<InputIterator>::value);
  51. detail::for_each_kernel<InputIterator, UnaryFunction> kernel(first, last, function);
  52. kernel.exec(queue);
  53. return function;
  54. }
  55. } // end compute namespace
  56. } // end boost namespace
  57. #endif // BOOST_COMPUTE_ALGORITHM_FOR_EACH_HPP