perf_thrust_saxpy.cu 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 <iostream>
  11. #include <iterator>
  12. #include <algorithm>
  13. #include <thrust/device_vector.h>
  14. #include <thrust/functional.h>
  15. #include <thrust/host_vector.h>
  16. #include <thrust/transform.h>
  17. #include "perf.hpp"
  18. struct saxpy_functor : public thrust::binary_function<float,float,float>
  19. {
  20. const float a;
  21. saxpy_functor(float _a) : a(_a) {}
  22. __host__ __device__
  23. float operator()(const float& x, const float& y) const
  24. {
  25. return a * x + y;
  26. }
  27. };
  28. int main(int argc, char *argv[])
  29. {
  30. perf_parse_args(argc, argv);
  31. std::cout << "size: " << PERF_N << std::endl;
  32. thrust::host_vector<int> host_x(PERF_N);
  33. thrust::host_vector<int> host_y(PERF_N);
  34. std::generate(host_x.begin(), host_x.end(), rand);
  35. std::generate(host_y.begin(), host_y.end(), rand);
  36. // transfer data to the device
  37. thrust::device_vector<int> device_x = host_x;
  38. thrust::device_vector<int> device_y = host_y;
  39. perf_timer t;
  40. for(size_t trial = 0; trial < PERF_TRIALS; trial++){
  41. t.start();
  42. thrust::transform(device_x.begin(), device_x.end(), device_y.begin(), device_y.begin(), saxpy_functor(2.5f));
  43. cudaDeviceSynchronize();
  44. t.stop();
  45. }
  46. std::cout << "time: " << t.min_time() / 1e6 << " ms" << std::endl;
  47. // transfer data back to host
  48. thrust::copy(device_x.begin(), device_x.end(), host_x.begin());
  49. thrust::copy(device_y.begin(), device_y.end(), host_y.begin());
  50. return 0;
  51. }