Shared Code

by pragya2720gupta·13 views·Jun 15, 2026Open in Playground →
main.cu
123456789101112131415161718192021222324252627282930313233343536373839404142
#include <stdio.h>


__global__ void vecAdd2D(float *a, float *b, float *c, int width, int height) { 
  int i = blockIdx.x * blockDim.x + threadIdx.x; int j = blockIdx.y * blockDim.y + threadIdx.y;
  if (i < width && j < height) 
  { int idx = j * width + i;
    c[idx] = a[idx] + b[idx];
  }
}

int main() { 
  int width = 32; 
  int height = 32; 
  size_t bytes = width * height * sizeof(float); // Allocate host memory 
  
  float *h_a = (float*)malloc(bytes); float *h_b = (float*)malloc(bytes); 
  float *h_c = (float*)malloc(bytes); // Initialize vectors 
  for (int x = 0; x < width; x++) { 
    for (int y = 0; y < height ; y++) { 
    int idx = y * width + x;
      h_a[idx] = idx * 1.0f;
      h_b[idx] = idx * 2.0f; 
    } 
  }
// Allocate device memory 
  float *d_a, *d_b, *d_c; 
  cudaMalloc(&d_a, bytes); 
  cudaMalloc(&d_b, bytes); 
  cudaMalloc(&d_c, bytes); // Copy data to GPU 
  cudaMemcpy(d_a, h_a, bytes, cudaMemcpyHostToDevice); 
  cudaMemcpy(d_b, h_b, bytes, cudaMemcpyHostToDevice); 
  dim3 threadsPerBlock(16, 16); // 16×16 = 256 threads 
  dim3 blocksPerGrid( (width + 15) / 16, (height + 15) / 16); 
  vecAdd2D<<<blocksPerGrid, threadsPerBlock>>>(d_a, d_b, d_c, width, height); // Copy result back to CPU 
  cudaMemcpy(h_c, d_c, bytes, cudaMemcpyDeviceToHost); // Verify 
  printf( "c[0]=%f c[last]=%f\n", h_c[0], h_c[(height - 1) * width + (width - 1)]); // Cleanup 
  cudaFree(d_a); cudaFree(d_b); cudaFree(d_c); 
  free(h_a); free(h_b); free(h_c); 
  return 0;
  
}

Comments (0)

to post comments and vote
No comments yet. Be the first to share your thoughts!