1 #include <unittest/unittest.h>
2 #include <thrust/pair.h>
3 #include <thrust/sort.h>
4 #include <thrust/transform.h>
5 #include <thrust/sequence.h>
6 #include <thrust/execution_policy.h>
7 
8 
9 template<typename ExecutionPolicy, typename Iterator1, typename Iterator2, typename Iterator3>
10 __global__
stable_sort_by_key_kernel(ExecutionPolicy exec,Iterator1 keys_first,Iterator1 keys_last,Iterator2 values_first,Iterator3 is_supported)11 void stable_sort_by_key_kernel(ExecutionPolicy exec, Iterator1 keys_first, Iterator1 keys_last, Iterator2 values_first, Iterator3 is_supported)
12 {
13 #if (__CUDA_ARCH__ >= 200)
14   *is_supported = true;
15   thrust::stable_sort_by_key(exec, keys_first, keys_last, values_first);
16 #else
17   *is_supported = false;
18 #endif
19 }
20 
21 
22 struct make_pair_functor
23 {
24   template<typename T1, typename T2>
25   __host__ __device__
operator ()make_pair_functor26     thrust::pair<T1,T2> operator()(const T1 &x, const T2 &y)
27   {
28     return thrust::make_pair(x,y);
29   } // end operator()()
30 }; // end make_pair_functor
31 
32 
33 template<typename ExecutionPolicy>
TestPairStableSortByKeyDevice(ExecutionPolicy exec)34 void TestPairStableSortByKeyDevice(ExecutionPolicy exec)
35 {
36   size_t n = 10000;
37   typedef thrust::pair<int,int> P;
38 
39   // host arrays
40   thrust::host_vector<int>   h_p1 = unittest::random_integers<int>(n);
41   thrust::host_vector<int>   h_p2 = unittest::random_integers<int>(n);
42   thrust::host_vector<P>   h_pairs(n);
43 
44   thrust::host_vector<int> h_values(n);
45   thrust::sequence(h_values.begin(), h_values.end());
46 
47   // zip up pairs on the host
48   thrust::transform(h_p1.begin(), h_p1.end(), h_p2.begin(), h_pairs.begin(), make_pair_functor());
49 
50   // device arrays
51   thrust::device_vector<P>   d_pairs = h_pairs;
52   thrust::device_vector<int> d_values = h_values;
53 
54   thrust::device_vector<bool> is_supported(1);
55 
56   // sort on the device
57   stable_sort_by_key_kernel<<<1,1>>>(exec, d_pairs.begin(), d_pairs.end(), d_values.begin(), is_supported.begin());
58   cudaError_t const err = cudaDeviceSynchronize();
59   ASSERT_EQUAL(cudaSuccess, err);
60 
61   if(is_supported[0])
62   {
63     // sort on the host
64     thrust::stable_sort_by_key(h_pairs.begin(), h_pairs.end(), h_values.begin());
65 
66     ASSERT_EQUAL_QUIET(h_pairs,  d_pairs);
67     ASSERT_EQUAL(h_values, d_values);
68   }
69 };
70 
71 
TestPairStableSortByKeyDeviceSeq()72 void TestPairStableSortByKeyDeviceSeq()
73 {
74   TestPairStableSortByKeyDevice(thrust::seq);
75 }
76 DECLARE_UNITTEST(TestPairStableSortByKeyDeviceSeq);
77 
78 
TestPairStableSortByKeyDeviceDevice()79 void TestPairStableSortByKeyDeviceDevice()
80 {
81   TestPairStableSortByKeyDevice(thrust::device);
82 }
83 DECLARE_UNITTEST(TestPairStableSortByKeyDeviceDevice);
84 
85