GPU Workshop Sample Code
 All Data Structures Namespaces Files Functions Variables Macros Pages
simpleThrust.cu
Go to the documentation of this file.
1 
9 #include <thrust/device_vector.h>
10 #include <thrust/transform.h>
11 #include <thrust/sequence.h>
12 #include <thrust/copy.h>
13 #include <thrust/fill.h>
14 #include <thrust/replace.h>
15 #include <thrust/functional.h>
16 #include <thrust/reduce.h>
17 #include <iostream>
18 #include <stdio.h>
19 
20 
21 
22 int main(void)
23 {
24  const int n = 1024;
25 
26  // allocate three device_vectors with 10 elements
27  thrust::device_vector<int> X(n);
28  thrust::device_vector<int> Y(n);
29  thrust::device_vector<int> Z(n);
30 
31  // initialize X to 0,1,2,3, ....
32  thrust::sequence(X.begin(), X.end());
33 
34  // compute Y = -X
35  thrust::transform(X.begin(), X.end(), Y.begin(), thrust::negate<int>());
36 
37  // fill Z with twos
38  thrust::fill(Z.begin(), Z.end(), 2);
39 
40  // compute Y = X mod 2
41  thrust::transform(X.begin(), X.end(), Z.begin(), Y.begin(), thrust::modulus<int>());
42 
43  // replace all the ones in Y with tens
44  thrust::replace(Y.begin(), Y.end(), 1, 10);
45 
46  // print Y
47  thrust::copy(Y.begin(), Y.begin()+20, std::ostream_iterator<int>(std::cout, "\n"));
48 
49  // reduction
50  thrust::device_vector<float> X2(n);
51  thrust::sequence( X2.begin(), X2.end() );
52  float xsum = thrust::reduce( X2.begin(), X2.end() );
53  printf( "sum is %12.1f\n", xsum );
54 
55  return 0;
56 }