心流logo

AskHN:如何开始使用CUDA

如何开始使用CUDA

CUDA(Compute Unified Device Architecture)是由NVIDIA开发的并行计算平台和编程模型,它允许开发者利用NVIDIA GPU的强大计算能力来加速计算密集型应用。以下是如何开始使用CUDA的详细指南。

1. 硬件和软件要求

1.1 硬件要求

1.2 软件要求

2. 安装CUDA Toolkit

2.1 下载CUDA Toolkit

2.2 安装CUDA Toolkit(Linux)

  1. 下载并解压安装包
wget https://developer.download.nvidia.com/compute/cuda/12.4.1/local_installers/cuda_12.4.1_550.54.15_linux.run
chmod +x cuda_12.4.1_550.54.15_linux.run
  1. 运行安装脚本
sudo ./cuda_12.4.1_550.54.15_linux.run
  1. 配置环境变量
echo 'export PATH=/usr/local/cuda/bin:$PATH' | sudo tee /etc/profile.d/cuda.sh
source /etc/profile
  1. 验证安装
nvcc --version

2.3 安装CUDA Toolkit(Windows)

  1. 下载并运行安装程序
  1. 自定义安装
  1. 验证安装
nvcc --version

3. 编写和运行CUDA程序

3.1 编写CUDA程序

以下是一个简单的CUDA程序示例,该程序在GPU上执行两个数组的加法操作:

#include <iostream>
#include <math.h>
// CUDA kernel to add two arrays
__global__ void add(int n, float *x, float *y) {
 for (int i = 0; i < n; i++) {
 y[i] = x[i] + y[i];
 }
}
int main(void) {
 int N = 1 << 20; // 1 million elements
 float *x, *y;
 // Allocate Unified Memory – accessible from CPU or GPU
 cudaMallocManaged(&x, N * sizeof(float));
 cudaMallocManaged(&y, N * sizeof(float));
 // Initialize x and y arrays on the host
 for (int i = 0; i < N; i++) {
 x[i] = 1.0f;
 y[i] = 2.0f;
 }
 // Run kernel on 1M elements on the GPU
 add<<<1, 1>>>(N, x, y);
 // Wait for GPU to finish before accessing on host
 cudaDeviceSynchronize();
 // Check for errors (all values should be 3.0f)
 float maxError = 0.0f;
 for (int i = 0; i < N; i++) {
 maxError = fmax(maxError, fabs(y[i] - 3.0f));
 }
 std::cout << "Max error: " << maxError << std::endl;
 // Free memory
 cudaFree(x);
 cudaFree(y);
 return 0;
}

3.2 编译和运行CUDA程序

  1. 保存代码:将上述代码保存为add.cu文件。
  2. 编译代码
nvcc add.cu -o add
nvcc add.cu -o add.exe
  1. 运行程序
./add
add.exe

4. CUDA编程基础

4.1 CUDA线程组织

4.2 内存管理