count_if.hpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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_COUNT_IF_HPP
  11. #define BOOST_COMPUTE_ALGORITHM_COUNT_IF_HPP
  12. #include <boost/static_assert.hpp>
  13. #include <boost/compute/device.hpp>
  14. #include <boost/compute/system.hpp>
  15. #include <boost/compute/command_queue.hpp>
  16. #include <boost/compute/algorithm/detail/count_if_with_ballot.hpp>
  17. #include <boost/compute/algorithm/detail/count_if_with_reduce.hpp>
  18. #include <boost/compute/algorithm/detail/count_if_with_threads.hpp>
  19. #include <boost/compute/algorithm/detail/serial_count_if.hpp>
  20. #include <boost/compute/detail/iterator_range_size.hpp>
  21. #include <boost/compute/type_traits/is_device_iterator.hpp>
  22. namespace boost {
  23. namespace compute {
  24. /// Returns the number of elements in the range [\p first, \p last)
  25. /// for which \p predicate returns \c true.
  26. ///
  27. /// Space complexity on CPUs: \Omega(1)<br>
  28. /// Space complexity on GPUs: \Omega(n)
  29. template<class InputIterator, class Predicate>
  30. inline size_t count_if(InputIterator first,
  31. InputIterator last,
  32. Predicate predicate,
  33. command_queue &queue = system::default_queue())
  34. {
  35. BOOST_STATIC_ASSERT(is_device_iterator<InputIterator>::value);
  36. const device &device = queue.get_device();
  37. size_t input_size = detail::iterator_range_size(first, last);
  38. if(input_size == 0){
  39. return 0;
  40. }
  41. if(device.type() & device::cpu){
  42. if(input_size < 1024){
  43. return detail::serial_count_if(first, last, predicate, queue);
  44. }
  45. else {
  46. return detail::count_if_with_threads(first, last, predicate, queue);
  47. }
  48. }
  49. else {
  50. if(input_size < 32){
  51. return detail::serial_count_if(first, last, predicate, queue);
  52. }
  53. else {
  54. return detail::count_if_with_reduce(first, last, predicate, queue);
  55. }
  56. }
  57. }
  58. } // end compute namespace
  59. } // end boost namespace
  60. #endif // BOOST_COMPUTE_ALGORITHM_COUNT_IF_HPP