Created
May 17, 2024 05:33
-
-
Save ravikul505/00483c8a62fa7aef61c91e250fd8adf8 to your computer and use it in GitHub Desktop.
cuda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
// Matrix dimensions | |
#define N 1024 | |
// CUDA kernel for matrix multiplication | |
__global__ void matrixMulKernel(float* A, float* B, float* C, int width) { | |
int row = blockIdx.y * blockDim.y + threadIdx.y; | |
int col = blockIdx.x * blockDim.x + threadIdx.x; | |
if (row < width && col < width) { | |
float value = 0; | |
for (int k = 0; k < width; ++k) { | |
value += A[row * width + k] * B[k * width + col]; | |
} | |
C[row * width + col] = value; | |
} | |
} | |
int main() { | |
// Host matrices | |
float *h_A, *h_B, *h_C; | |
// Device matrices | |
float *d_A, *d_B, *d_C; | |
int size = N * N * sizeof(float); | |
// Allocate host memory | |
h_A = (float*)malloc(size); | |
h_B = (float*)malloc(size); | |
h_C = (float*)malloc(size); | |
// Initialize host matrices | |
for (int i = 0; i < N * N; ++i) { | |
h_A[i] = 1.0f; // Example values | |
h_B[i] = 1.0f; // Example values | |
} | |
// Allocate device memory | |
cudaMalloc((void**)&d_A, size); | |
cudaMalloc((void**)&d_B, size); | |
cudaMalloc((void**)&d_C, size); | |
// Copy host matrices to device | |
cudaMemcpy(d_A, h_A, size, cudaMemcpyHostToDevice); | |
cudaMemcpy(d_B, h_B, size, cudaMemcpyHostToDevice); | |
// Define block and grid dimensions | |
dim3 dimBlock(16, 16); | |
dim3 dimGrid((N + dimBlock.x - 1) / dimBlock.x, (N + dimBlock.y - 1) / dimBlock.y); | |
// Launch the kernel | |
matrixMulKernel<<<dimGrid, dimBlock>>>(d_A, d_B, d_C, N); | |
// Copy result matrix back to host | |
cudaMemcpy(h_C, d_C, size, cudaMemcpyDeviceToHost); | |
// Print the result (optional) | |
// for (int i = 0; i < N; ++i) { | |
// for (int j = 0; j < N; ++j) { | |
// printf("%0.2f ", h_C[i * N + j]); | |
// } | |
// printf("\n"); | |
// } | |
// Free device memory | |
cudaFree(d_A); | |
cudaFree(d_B); | |
cudaFree(d_C); | |
// Free host memory | |
free(h_A); | |
free(h_B); | |
free(h_C); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment