__global__ void matrixMultiply(float *A, float *B, float *C, int N) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
float sum = 0.0;
for (int i = 0; i < N; i++) {
sum += A[row * N + i] * B[i * N + col];
}
C[row * N + col] = sum;
}
int main() {
// Allocate memory for matrices A, B, and C on the GPU
float *A, *B, *C;
cudaMalloc((void **)&A, N * N * sizeof(float));
cudaMalloc((void **)&B, N * N * sizeof(float));
cudaMalloc((void **)&C, N * N * sizeof(float));
// Initialize matrices A and B with random values
// ...
// Launch the matrix multiplication kernel
dim3 blockSize(16, 16, 1);
dim3 gridSize((N + blockSize.x - 1) / blockSize.x, (N + blockSize.y - 1) / blockSize.y, 1);
matrixMultiply<<<gridSize, blockSize>>>(A, B, C, N);
// Copy the result matrix C back to the host
cudaMemcpy(C, C, N * N * sizeof(float), cudaMemcpyDeviceToHost);
// Free the memory allocated on the GPU
cudaFree(A);
cudaFree(B);
cudaFree(C);
return 0;
}
This code defines a matrix multiplication kernel that multiplies two matrices A and B and stores the result in a third matrix C. The kernel is launched with a grid of blocks and threads, with each thread computing one element of the result matrix C. The number of threads in each block is specified by the blockSize variable, and the number of blocks in the grid is determined by the size of the matrices and the block size.
The main function allocates memory for the matrices on the GPU, initializes the matrices with random values, launches the kernel, and copies the result matrix C back to the host. Finally, it frees the memory allocated on the GPU.