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