1 //---------------------------------------------------------------------------//
2 // Copyright (c) 2013-2014 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 #include <algorithm>
12 #include <iostream>
13 #include <vector>
14
15 #include <boost/compute/system.hpp>
16 #include <boost/compute/algorithm/copy.hpp>
17 #include <boost/compute/algorithm/transform.hpp>
18 #include <boost/compute/container/vector.hpp>
19
20 namespace compute = boost::compute;
21
22 // this example shows how to embed PTX assembly instructions
23 // directly into boost.compute functions and use them with the
24 // transform() algorithm.
main()25 int main()
26 {
27 // get default device and setup context
28 compute::device gpu = compute::system::default_device();
29 compute::context context(gpu);
30 compute::command_queue queue(context, gpu);
31 std::cout << "device: " << gpu.name() << std::endl;
32
33 // check to ensure we have an nvidia device
34 if(gpu.vendor() != "NVIDIA Corporation"){
35 std::cerr << "error: inline PTX assembly is only supported "
36 << "on NVIDIA devices."
37 << std::endl;
38 return 0;
39 }
40
41 // create input values and copy them to the device
42 using compute::uint_;
43 uint_ data[] = { 0x00, 0x01, 0x11, 0xFF };
44 compute::vector<uint_> input(data, data + 4, queue);
45
46 // function returning the number of bits set (aka population count or
47 // popcount) using the "popc" inline ptx assembly instruction.
48 BOOST_COMPUTE_FUNCTION(uint_, nvidia_popc, (uint_ x),
49 {
50 uint count;
51 asm("popc.b32 %0, %1;" : "=r"(count) : "r"(x));
52 return count;
53 });
54
55 // calculate the popcount for each input value
56 compute::vector<uint_> output(input.size(), context);
57 compute::transform(
58 input.begin(), input.end(), output.begin(), nvidia_popc, queue
59 );
60
61 // copy results back to the host and print them out
62 std::vector<uint_> counts(output.size());
63 compute::copy(output.begin(), output.end(), counts.begin(), queue);
64
65 for(size_t i = 0; i < counts.size(); i++){
66 std::cout << "0x" << std::hex << data[i]
67 << " has " << counts[i]
68 << " bits set" << std::endl;
69 }
70
71 return 0;
72 }
73