this example shows how to embed PTX assembly instructions directly into boost.compute functions and use them with the transform() algorithm.
| 23 | // directly into boost.compute functions and use them with the |
| 24 | // transform() algorithm. |
| 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 | } |