CUDA 核函数示例:使用 mykernel 将 src 数据复制到 dst

本文提供了一个 CUDA 核函数 mykernel 的示例,该函数使用 foo 参数将 src 数据复制到 dst。代码展示了如何使用 CUDA API 分配内存、将数据从主机复制到设备、启动内核、将数据从设备复制回主机以及验证结果。

示例代码

#include <cuda_runtime.h>
#include <cstdio>

__global__ void mykernel(int *dst, int *src) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    dst[i] = src[i];
}

int main() {
    int n = 10;
    int *host_src = new int[n];
    int *host_dst = new int[n];
    int *device_src, *device_dst;

    // Allocate memory on device
    cudaMalloc(&device_src, n * sizeof(int));
    cudaMalloc(&device_dst, n * sizeof(int));

    // Initialize host data
    for (int i = 0; i < n; i++) {
        host_src[i] = i;
        host_dst[i] = 0;
    }

    // Copy host data to device
    cudaMemcpy(device_src, host_src, n * sizeof(int), cudaMemcpyHostToDevice);

    // Launch kernel
    int blocksize = 256;
    int gridsize = (n + blocksize - 1) / blocksize;
    mykernel<<<gridsize, blocksize>>>(device_dst, device_src);

    // Copy device data to host
    cudaMemcpy(host_dst, device_dst, n * sizeof(int), cudaMemcpyDeviceToHost);

    // Verify result
    for (int i = 0; i < n; i++) {
        if (host_dst[i] != host_src[i]) {
            printf("Error: host_dst[%d] = %d, host_src[%d] = %d\n", i, host_dst[i], i, host_src[i]);
            break;
        }
    }

    // Free memory
    cudaFree(device_src);
    cudaFree(device_dst);
    delete[] host_src;
    delete[] host_dst;

    return 0;
}

代码解释

  • global void mykernel(int *dst, int *src):定义了一个名为 mykernel 的 CUDA 核函数,它接收两个整型指针作为参数,分别代表目标数据 dst 和源数据 src。

  • int i = blockIdx.x * blockDim.x + threadIdx.x:每个线程都会执行此语句,计算当前线程的索引 i。

  • dst[i] = src[i]:每个线程将 src 中对应索引的值复制到 dst 中。

  • cudaMalloc(&device_src, n * sizeof(int))cudaMalloc(&device_dst, n * sizeof(int)):分别在设备上分配 n 个整型大小的内存空间,用于存储源数据和目标数据。

  • cudaMemcpy(device_src, host_src, n * sizeof(int), cudaMemcpyHostToDevice):将主机上的源数据复制到设备上的内存中。

  • mykernel<<<gridsize, blocksize>>>(device_dst, device_src):启动 mykernel 核函数,使用 gridsize 和 blocksize 分别指定网格和块的大小。

  • cudaMemcpy(host_dst, device_dst, n * sizeof(int), cudaMemcpyDeviceToHost):将设备上的目标数据复制回主机上的内存中。

  • for (int i = 0; i < n; i++):验证结果,比较主机上的源数据和目标数据是否相同。

  • cudaFree(device_src)cudaFree(device_dst):释放设备上的内存。

  • delete[] host_srcdelete[] host_dst:释放主机上的内存。

总结

本示例展示了使用 CUDA 核函数进行数据复制的基本步骤,包括内存分配、数据传输、启动内核和结果验证。您可以根据自己的需求修改代码,例如更改数据类型、使用不同的数据大小或添加更复杂的核函数逻辑。

CUDA 核函数示例:使用 mykernel 将 src 数据复制到 dst

原文地址: https://www.cveoy.top/t/topic/ntCA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录