serial_count_if.hpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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_COUNT_IF_HPP
  11. #define BOOST_COMPUTE_ALGORITHM_DETAIL_SERIAL_COUNT_IF_HPP
  12. #include <iterator>
  13. #include <boost/compute/container/detail/scalar.hpp>
  14. #include <boost/compute/detail/meta_kernel.hpp>
  15. #include <boost/compute/detail/iterator_range_size.hpp>
  16. namespace boost {
  17. namespace compute {
  18. namespace detail {
  19. // counts values that match the predicate using a single thread
  20. template<class InputIterator, class Predicate>
  21. inline size_t serial_count_if(InputIterator first,
  22. InputIterator last,
  23. Predicate predicate,
  24. command_queue &queue)
  25. {
  26. typedef typename std::iterator_traits<InputIterator>::value_type value_type;
  27. const context &context = queue.get_context();
  28. size_t size = iterator_range_size(first, last);
  29. meta_kernel k("serial_count_if");
  30. k.add_set_arg("size", static_cast<uint_>(size));
  31. size_t result_arg = k.add_arg<uint_ *>(memory_object::global_memory, "result");
  32. k <<
  33. "uint count = 0;\n" <<
  34. "for(uint i = 0; i < size; i++){\n" <<
  35. k.decl<const value_type>("value") << "="
  36. << first[k.var<uint_>("i")] << ";\n" <<
  37. "if(" << predicate(k.var<const value_type>("value")) << "){\n" <<
  38. "count++;\n" <<
  39. "}\n"
  40. "}\n"
  41. "*result = count;\n";
  42. kernel kernel = k.compile(context);
  43. // setup result buffer
  44. scalar<uint_> result(context);
  45. kernel.set_arg(result_arg, result.get_buffer());
  46. // run kernel
  47. queue.enqueue_task(kernel);
  48. // read index
  49. return result.read(queue);
  50. }
  51. } // end detail namespace
  52. } // end compute namespace
  53. } // end boost namespace
  54. #endif // BOOST_COMPUTE_ALGORITHM_DETAIL_SERIAL_COUNT_IF_HPP