如何在CUDA中使用2D阵列?
我是CUDA的新手。如何分配大小为MXN?的2D数组?。如何在CUDA中遍历该数组?。给我一个示例代码。 徖 你好,谢谢你的回复。我在下面的程序中使用了你的代码。但我没有得到正确的结果如何在CUDA中使用2D阵列?,cuda,Cuda,我是CUDA的新手。如何分配大小为MXN?的2D数组?。如何在CUDA中遍历该数组?。给我一个示例代码。 徖 你好,谢谢你的回复。我在下面的程序中使用了你的代码。但我没有得到正确的结果 __global__ void test(int A[BLOCK_SIZE][BLOCK_SIZE], int B[BLOCK_SIZE][BLOCK_SIZE],int C[BLOCK_SIZE][BLOCK_SIZE]) { int i = blockIdx.y * blockDim.y + thr
__global__ void test(int A[BLOCK_SIZE][BLOCK_SIZE], int B[BLOCK_SIZE][BLOCK_SIZE],int C[BLOCK_SIZE][BLOCK_SIZE])
{
int i = blockIdx.y * blockDim.y + threadIdx.y;
int j = blockIdx.x * blockDim.x + threadIdx.x;
if (i < BLOCK_SIZE && j < BLOCK_SIZE)
C[i][j] = A[i][j] + B[i][j];
}
int main()
{
int d_A[BLOCK_SIZE][BLOCK_SIZE];
int d_B[BLOCK_SIZE][BLOCK_SIZE];
int d_C[BLOCK_SIZE][BLOCK_SIZE];
int C[BLOCK_SIZE][BLOCK_SIZE];
for(int i=0;i<BLOCK_SIZE;i++)
for(int j=0;j<BLOCK_SIZE;j++)
{
d_A[i][j]=i+j;
d_B[i][j]=i+j;
}
dim3 dimBlock(BLOCK_SIZE, BLOCK_SIZE);
dim3 dimGrid(GRID_SIZE, GRID_SIZE);
test<<<dimGrid, dimBlock>>>(d_A,d_B,d_C);
cudaMemcpy(C,d_C,BLOCK_SIZE*BLOCK_SIZE , cudaMemcpyDeviceToHost);
for(int i=0;i<BLOCK_SIZE;i++)
for(int j=0;j<BLOCK_SIZE;j++)
{
printf("%d\n",C[i][j]);
}
}
\uuuuu全局无效测试(int A[块大小][块大小]、int B[块大小][块大小]、int C[块大小][块大小])
{
int i=blockIdx.y*blockDim.y+threadIdx.y;
int j=blockIdx.x*blockDim.x+threadIdx.x;
如果(i 对于(int i=0;i如何分配2D数组:
int main(){
#define BLOCK_SIZE 16
#define GRID_SIZE 1
int d_A[BLOCK_SIZE][BLOCK_SIZE];
int d_B[BLOCK_SIZE][BLOCK_SIZE];
/* d_A initialization */
dim3 dimBlock(BLOCK_SIZE, BLOCK_SIZE); // so your threads are BLOCK_SIZE*BLOCK_SIZE, 256 in this case
dim3 dimGrid(GRID_SIZE, GRID_SIZE); // 1*1 blocks in a grid
YourKernel<<<dimGrid, dimBlock>>>(d_A,d_B); //Kernel invocation
}
我希望这是有帮助的
您也可以参考第22页关于矩阵乘法的内容,最好的方法是以向量形式存储二维数组a。
例如,您有一个大小为nxm的矩阵,它在指针到指针表示中的(i,j)元素将是
A[i][j] (with i=0..n-1 and j=0..m-1).
你可以用向量的形式写
A[i*n+j] (with i=0..n-1 and j=0..m-1).
在这种情况下,使用一维数组将简化复制过程,这将非常简单:
double *A,*dev_A; //A-hous pointer, dev_A - device pointer;
A=(double*)malloc(n*m*sizeof(double));
cudaMalloc((void**)&dev_A,n*m*sizeof(double));
cudaMemcpy(&dev_A,&A,n*m*sizeof(double),cudaMemcpyHostToDevice); //In case if A is double
你可以更礼貌一点,这不会伤害你。你不能用cudaMemcpy收回2D数组的值,相反,你必须用cudamalocpictch或cudaPitchPtr将cudamaloc3d作为@Davesaid@user621508虽然这会起作用,但它只会在设备内存中创建一个巨大的线性阵列对2D数据访问进行了优化。我不知道您是想要2D数组的索引还是性能。@username\u 4567,这就是/*d\u a initialization*/的意思。但是没有内存释放。/*d\u a initialization*/的实际内容也是答案的一个重要部分。您能提供它吗?
double *A,*dev_A; //A-hous pointer, dev_A - device pointer;
A=(double*)malloc(n*m*sizeof(double));
cudaMalloc((void**)&dev_A,n*m*sizeof(double));
cudaMemcpy(&dev_A,&A,n*m*sizeof(double),cudaMemcpyHostToDevice); //In case if A is double