Advertisement
R3P3T

Untitled

Jan 26th, 2021
940
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.20 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <cuda.h>
  4. #define TAM_BLOCK 256
  5.  
  6. __global__ void stencil2d(int *a_d, int *b_d){
  7.   unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;
  8.   unsigned int j = blockIdx.y * blockDim.y + threadIdx.y;
  9.  
  10.   b_d[i*j+i] = 0.2f * (a_d[i*j+i]) + a_d[(i*j-1)+i] + a_d[(i*j)+i-1] + a_d[(i*j+1)+i] + a_d[(i*j)+i+1];
  11.  
  12. }
  13.  
  14. int main(){
  15.   int *a,*gpu,k, *b, *a_d, *b_d, filas, columnas,i,j,iteraciones;
  16.  
  17.   printf("Escribe el numero de iteraciones: "); scanf("%d",&iteraciones);
  18.   printf("Escribe el numero de filas: "); scanf("%d",&filas);
  19.   printf("Escribe el numero de columnas: "); scanf("%d",&columnas);
  20.  
  21.   a = (int*) malloc(sizeof(int) * filas * columnas);
  22.   b = (int*) malloc(sizeof(int) * filas * columnas);
  23.   gpu = (int*) malloc(sizeof(int) * filas * columnas);
  24.  
  25.   for(i = 0; i < filas; i++){
  26.     for(j = 0; j < columnas; j++){
  27.       a[i*j+i] = rand() % 100;
  28.       b[i*j+i] = 0;
  29.     }
  30.   }
  31.   for(k = 0; k < iteraciones; k++){
  32.      for(i = 1; i < (filas-1); i++){
  33.         for(j = 1; j < (columnas-1); j++){
  34.             gpu[i*j+i] = 0.2f*(a[i*j+i]) + a[(i*j-1)+i] + a[(i*j)+i-1] + a[(i*j+1)+i] + a[(i*j)+i+1];
  35.         printf("b[%d][%d] = %d\t",i,j,gpu[i*j+i]);
  36.         }
  37.      printf("\n");
  38.     }
  39.   }
  40.  
  41.   cudaSetDevice(0);
  42.  
  43.   cudaMalloc((void **) &a_d, sizeof(int) * filas * columnas);
  44.   cudaMalloc((void **) &b_d, sizeof(int) * filas * columnas);
  45.  
  46.   cudaMemcpy(a_d,a, sizeof(int) * filas * columnas, cudaMemcpyHostToDevice);
  47.   cudaMemcpy(b_d,b, sizeof(int) * filas * columnas, cudaMemcpyHostToDevice);
  48.  
  49.   dim3 thread(TAM_BLOCK,TAM_BLOCK);
  50.   dim3 bloques((((filas-2)/TAM_BLOCK)+1),(((columnas-2)/TAM_BLOCK)+1));
  51.  
  52.   for(k = 0; k < iteraciones; k++){
  53.     stencil2d<<<bloques,thread>>> (a_d,b_d);
  54.   }
  55.  
  56.   cudaMemcpy(b,b_d, sizeof(int) * filas * columnas, cudaMemcpyDeviceToHost);
  57.  
  58.   for(k = 0; k < iteraciones; k++){
  59.     for(i = 1; i < (filas-1); i++){
  60.       for(j = 1; j < (filas-1); j++){
  61.         printf("b[%d][%d] = %d\t",i,j,b[i*j+i]);
  62.       }
  63.       printf("\n");
  64.     }
  65.   }
  66. }
  67.                                                                                                                                                                                                  
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement