#include <cuda_runtime.h> #include <iostream> __global__ void vector_add_kernel(const float* a, const float* b, float* c, int n) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) { c[i] = a[i] + b[i]; } } void vector_add(co
时间: 2025-03-13 15:13:14 浏览: 45
### CUDA C++ 向量加法 Kernel 完整示例及主机端调用代码
以下是完整的 CUDA C++ 实现向量加法的代码示例,包括 GPU 内核函数定义以及主机端调用部分。
#### 1. GPU 内核函数 (Kernel Function)
```cpp
__global__
void vectorAdd(const float* A, const float* B, float* C, int N) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < N) {
C[i] = A[i] + B[i];
}
}
```
上述代码展示了 `vectorAdd` 的实现方式。这是一个典型的 CUDA 内核函数,其中线程索引通过组合 `blockIdx.x`, `blockDim.x` 和 `threadIdx.x` 来计算[^3]。每个线程负责处理数组中的一个元素,并将其存储到结果数组中。
---
#### 2. 主机端调用代码 (Host Code)
以下为主机端代码,它包含了设备内存分配、数据传输、内核启动和结果验证的过程:
```cpp
#include <iostream>
#include <cuda_runtime.h>
#define CHECK_ERROR(err) \
if (err != cudaSuccess) { \
std::cerr << "Cuda error: " << cudaGetErrorString(err) << std::endl; \
exit(EXIT_FAILURE); \
}
int main() {
int N = 1 << 20; // Number of elements
size_t bytes = N * sizeof(float);
// Allocate host memory
float* h_A = (float*)malloc(bytes);
float* h_B = (float*)malloc(bytes);
float* h_C = (float*)malloc(bytes);
// Initialize input data on the host
for (int i = 0; i < N; ++i) {
h_A[i] = rand() / (float)RAND_MAX;
h_B[i] = rand() / (float)RAND_MAX;
}
// Allocate device memory
float* d_A = nullptr;
float* d_B = nullptr;
float* d_C = nullptr;
cudaError_t err = cudaMalloc((void**)&d_A, bytes);
CHECK_ERROR(err);
err = cudaMalloc((void**)&d_B, bytes);
CHECK_ERROR(err);
err = cudaMalloc((void**)&d_C, bytes);
CHECK_ERROR(err);
// Copy data from host to device
err = cudaMemcpy(d_A, h_A, bytes, cudaMemcpyHostToDevice);
CHECK_ERROR(err);
err = cudaMemcpy(d_B, h_B, bytes, cudaMemcpyHostToDevice);
CHECK_ERROR(err);
// Define execution configuration parameters
int threadsPerBlock = 256;
int blocksPerGrid = (N + threadsPerBlock - 1) / threadsPerBlock;
// Launch kernel
vectorAdd<<<blocksPerGrid, threadsPerBlock>>>(d_A, d_B, d_C, N);
err = cudaGetLastError();
CHECK_ERROR(err);
// Synchronize and check for errors after kernel launch
err = cudaDeviceSynchronize();
CHECK_ERROR(err);
// Copy result back to host
err = cudaMemcpy(h_C, d_C, bytes, cudaMemcpyDeviceToHost);
CHECK_ERROR(err);
// Verify results
bool success = true;
for (int i = 0; i < N; ++i) {
if (fabsf(h_A[i] + h_B[i] - h_C[i]) > 1e-5) {
success = false;
break;
}
}
if (success) {
std::cout << "Test PASSED!" << std::endl;
} else {
std::cout << "Test FAILED!" << std::endl;
}
// Free allocated resources
free(h_A);
free(h_B);
free(h_C);
cudaFree(d_A);
cudaFree(d_B);
cudaFree(d_C);
return 0;
}
```
此代码片段实现了完整的向量加法流程。其中包括了设备内存管理、数据拷贝操作以及错误检测机制[^1]。此外,还提供了简单的结果校验逻辑来确认计算准确性。
---
### 编译命令
为了编译该程序,可以使用 NVCC 提供的标准编译选项:
```bash
nvcc vector_add.cu -o vector_add
```
这一步骤会生成可执行文件 `vector_add`,随后可以通过运行该文件测试其功能。
---
### 调试工具说明
如果需要调试此程序,则可以在 Host 端利用标准 GDB 命令完成;而在 Device 端则需借助特定于 CUDA 的调试指令集,例如但不限于 `cuda thread`, `lane`, 或者其他与硬件结构紧密关联的概念[^2]。
---
阅读全文
相关推荐















