我开始学习 CUDA,我想编写一个简单的程序,将一些数据复制到 GPU,对其进行修改,然后将其传回。我已经用谷歌搜索并试图找到我的错误。我很确定问题出在我的内核中,但我不完全确定出了什么问题。
这是我的内核:
__global__ void doStuff(float* data, float* result)
{
if (threadIdx.x < 9) // take the first 9 threads
{
int index = threadIdx.x;
result[index] = (float) index;
}
}
以下是我的相关部分main
:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
/*
Setup
*/
float simple[] = {-1.0, -2.0, -3.0, -4.0, -5.0, -6.0, -7.0, -8.0, -9.0};
float* data_array;
float* result_array;
size_t data_array_pitch, result_array_pitch;
int width_in_bytes = 3 * sizeof(float);
int height = 3;
/*
Initialize GPU arrays
*/
cudaMallocPitch(&data_array, &data_array_pitch, width_in_bytes, height);
cudaMallocPitch(&result_array, &result_array_pitch, width_in_bytes, height);
/*
Copy data to GPU
*/
cudaMemcpy2D(data_array, data_array_pitch, simple, width_in_bytes, width_in_bytes, height, cudaMemcpyHostToDevice);
dim3 threads_per_block(16, 16);
dim3 num_blocks(1,1);
/*
Do stuff
*/
doStuff<<<num_blocks, threads_per_blocks>>>(data_array, result_array);
/*
Get the results
*/
cudaMemcpy2D(simple, width_in_bytes, result_array, result_array_pitch, width_in_bytes, height, cudaMemcpyDeviceToHost);
for (int i = 1; i <= 9; ++i)
{
printf("%f ", simple[i-1]);
if(!(i%3))
printf("\n");
}
return 0;
}
当我运行它时,我得到0.000000 1.000000 2.00000
第一行和其他两行的垃圾。