我正在使用 cuda 来加速我的代码,其中我循环处理每个图像。每个图像都通过 cuda 在 GPU 上进行处理。
我参考cuda-samples编写了以下代码:
- 文件名:
my_cuda.cu
#include "cuda_runtime.h"
int process_one_image(args)
{
// note that declaration of some params is omitted.
unsigned char *h_data = (unsigned char *)malloc(size);
unsigned char *h_rgb = (unsigned char *)malloc(size_result);
// initialize the host memory as an image info.
...
unsigned char *d_data;
unsigned char *d_rgb;
cudaMalloc((void **)&d_data, size);
cudaMalloc((void **)&d_rgb, size_result);
cudaMemcpy(d_data, h_data, size, cudaMemcpyHostToDevice);
// process the d_data on GPU
...
// copy the result from device to host.
cudaMemcpy(h_rgb, d_rgb, size_result, cudaMemcpyDeviceToHost);
free(h_rgb);
free(h_data)
cudaFree(d_rgb);
cudaFree(d_data);
}
在上面的代码中,cudaMalloc
和cudaMemcpy
位于同一个函数中process_one_image
。并且代码运行正确。
但我想重复运行这段代码,例如循环运行超过 10000 次。所以我不想每次处理图像时都cudaMalloc
这样做。cudaFree
所以我想将我的代码更改为以下安排。
- cuda_文件:
my_cuda.cu
#include "cuda_runtime.h"
int initCuda(unsigned char *h_data, unsigned char *h_rgb, unsigned char *d_data, unsigned char *d_rgb)
{
// note that declaration of some params is omitted.
unsigned char *h_data = (unsigned char *)malloc(size);
unsigned char *h_rgb = (unsigned char *)malloc(size_result);
cudaMalloc((void **)&d_data, size);
cudaMalloc((void **)&d_rgb, size);
}
int FinalizeCuda(unsigned char *h_data, unsigned char *h_rgb, unsigned char *d_data, unsigned char *d_rgb)
{
cudaFree(d_data);
cudaFree(d_rgb);
free(h_data);
free(h_rgb);
}
int process_one_image(unsigned char *h_data, unsigned char *h_rgb, unsigned char *d_data, unsigned char *d_rgb) // note some args are omitted such as size etc.
{
cudaMemcpy(d_data, h_data, size, cudaMemcpyHostToDevice);
// process the d_data on GPU
...
// copy the result from device to host.
cudaMemcpy(h_rgb, d_rgb, size, cudaMemcpyDeviceToHost);
}
- 我的c代码:
c_code.c
#include "my_cuda.cu"
int processing_loop(args) // specific args are omitted
{
// declaration of host and device memory
unsigned char *h_data;
unsigned char *h_rgb;
unsigned char *d_data;
unsigned char *d_rgb;
initCuda(h_data, h_rgb, d_data, d_rgb);
while (1)
{
int ret = process_one_image(h_data, h_rgb, d_data, d_rgb);
}
FinalizeCuda(h_data, h_rgb, d_data, d_rgb);
}
在这里,您可以注意到我只想cudaMalloc
在 C 文件中运行一次,以加速此代码,但我发现它无法正常工作。它没有报告任何错误,但我没有从h_rgb
.
看来(我猜)在处理时 cudaMemcpy
,它无法找到正确的地址d_data
并复制到d_data。
那么我该如何修复这个错误,或者cudaMalloc
,这是只执行一次的正确方法吗?
整个代码位于ffio key_file_path中:
ffio/ffio/ffio_c/ffio.c
- 对应于c_code.c
示例文件。ffio/ffio/ffio_c/yuv2rgb.cu
- 对应于my_cuda.cu
示例。
如何运行整个示例:
./compiler.sh
构建可执行文件main
- 执行
main
位于ffio/ffio/ffio_c/test
ffio->cudaFrame
使用 Ctrl+F检查变量
基本 C/C++:您希望
initCuda
函数在函数中设置指针processing_loop
。所以你必须将一个指针传递给函数的指针initCuda
。这是一个最小的修复。请注意,您的代码还存在其他问题,例如缺少错误检查。