inline_ptx.cpp 2.4 KB

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