florianscholz

Untitled

Mar 18th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <vector>
  2. #include <algorithm>
  3. #include <boost/compute.hpp>
  4.  
  5. namespace compute = boost::compute;
  6.  
  7.  
  8. const char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(
  9.         __kernel void vectorAdd(__global const float *a,
  10.                                 __global const float *b,
  11.                                 __global float *c)
  12.         {
  13.            int i=get_global_id(0);
  14.            c[i]=a[i]+b[i];
  15.         });
  16.  
  17. int main()
  18. {
  19.     // get the default compute device
  20.     compute::device gpu = compute::system::default_device();
  21.  
  22.     // create a compute context and command queue
  23.     compute::context ctx(gpu);
  24.     compute::command_queue queue(ctx, gpu);
  25.  
  26.  
  27.     compute::program program = compute::program::build_with_source(source, ctx);
  28.     compute::kernel kernel = program.create_kernel("vectorAdd");
  29.  
  30.     // generate random numbers on the host
  31.     std::vector<float> host_vector(5);
  32.     std::generate(host_vector.begin(), host_vector.end(), rand);
  33.  
  34.     // create vector on the device
  35.     compute::vector<float> device_vector(5, ctx);
  36.     compute::vector<float> device_vector_out(5, ctx);
  37.  
  38.     // copy data to the device
  39.     compute::copy(
  40.         host_vector.begin(), host_vector.end(), device_vector.begin(), queue
  41.     );
  42.  
  43.     kernel.set_arg(0, device_vector);
  44.     kernel.set_arg(1, device_vector);
  45.     kernel.set_arg(2, device_vector_out);
  46.  
  47.     std::cout << "before addition" << std::endl;
  48.     for(auto a : host_vector) {
  49.         std::cout << a << std::endl;
  50.     }
  51.  
  52.  
  53.     queue.enqueue_1d_range_kernel(kernel, 0, 5, 1);
  54.     queue.finish();
  55.  
  56.     std::vector<float> host_out(5);
  57.     compute::copy(device_vector_out.begin(), device_vector_out.end(), host_out.begin(), queue);
  58.  
  59.     std::cout << "sorted" << std::endl;
  60.     for(auto a : host_out) {
  61.         std::cout << a << std::endl;
  62.     }
  63.  
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment