2011-02-17 57 views
15

我是CUDA的新手。如何分配MXN大小的二维数组?如何在CUDA中遍历该数组?给我一个示例代码。 ................................................. ...........................................如何在CUDA中使用2D阵列?

嗨..感谢您的回复。我在以下程序中使用了您的代码。但我没有得到正确的结果。

__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]); 

     } 
} 

请帮帮我。

+16

你可能会更有礼貌,它不会伤害你。 – karlphillip 2011-02-17 14:28:59

+1

你不能用cudaMemcpy取回二维数组的值,而必须使用cudaMallocPitch或cudaPitchPtr与cudaMalloc3D,因为@Dave表示 – ardiyu07 2011-02-17 17:26:35

回答

16

如何分配二维数组:

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 
} 

如何遍历数组:

__global__ void YourKernel(int d_A[BLOCK_SIZE][BLOCK_SIZE], int d_B[BLOCK_SIZE][BLOCK_SIZE]){ 
int row = blockIdx.y * blockDim.y + threadIdx.y; 
int col = blockIdx.x * blockDim.x + threadIdx.x; 
if (row >= h || col >= w)return; 
/* whatever you wanna do with d_A[][] and d_B[][] */ 
} 

我希望这是有益

,你也可以参考22 CUDA Programming Guide页约矩阵乘法

4

最好的方法是存储一个双精度数据,以其向量形式的二维数组A. 例如,你有一个矩阵A的大小n×m个,和它的(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