Advertisement
Guest User

sum_vector_block.cu

a guest
Apr 4th, 2015
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <iostream>
  3. #define N 1024
  4. using namespace std;
  5.  
  6. __global__ void vectorAdd(int *a, int *b, int *c) {
  7.     int i = blockIdx.x;
  8.     c[i] = a[i] + b[i];
  9. }
  10.  
  11. // create random numbers and put on the vector
  12. void randomInts(int *vector) {
  13.     int i = 0;
  14.     time_t t;
  15.     srand((unsigned) time(&t));
  16.     for (; i < N; i++)
  17.         vector[i] = rand() % 1000 + 1;
  18. }
  19.  
  20. int main() {
  21.     int *a, *b, *c, i = 0;
  22.     int *d_a, *d_b, *d_c;
  23.     int size = N * sizeof(int);
  24.  
  25.     a = (int *) malloc(size); randomInts(a);
  26.     b = (int *) malloc(size); randomInts(b);
  27.     c = (int *) malloc(size);
  28.  
  29.     cudaMalloc(&d_a, size);
  30.     cudaMalloc(&d_b, size);
  31.     cudaMalloc(&d_c, size);
  32.  
  33.     cudaMemcpy(d_a, a, size, cudaMemcpyHostToDevice);
  34.     cudaMemcpy(d_b, b, size, cudaMemcpyHostToDevice);
  35.  
  36.     vectorAdd<<<N,1>>>(d_a, d_b, d_c);
  37.  
  38.     cudaMemcpy(c, d_c, size, cudaMemcpyDeviceToHost);
  39.  
  40.     // printing the first ten number of result vector
  41.     for (; i < 10; ++i)
  42.         cout << "c[" << i << "] = " << c[i] << endl;
  43.  
  44.     free(a); free(b); free(c);
  45.     cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);
  46.  
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement