简体   繁体   English

在 cuda GPU cudamalloc 中将 3D 数组转换为 1D

[英]convert 3D array to 1D in cuda GPU cudamalloc

My problem is this: I have an array in 3D and I cannot use the malloc3D, and I need to convert and manipulate 1D array on GPU.我的问题是:我有一个 3D 数组,我不能使用 malloc3D,我需要在 GPU 上转换和操作一维数组。 But I don't know how do it.但我不知道怎么做。 In this moment I am using在这一刻我正在使用

#define nx  8
#define ny  6
#define nz  4

to define the matriz array.. 4 matrices of 6 row with 8 columns with index i,j,k.定义矩阵数组.. 4 个矩阵,6 行,8 列,索引为 i,j,k。

u[i][j][k]

and I declaration of:我声明:

cudaMalloc( (void**)&dev_u, ny * nx * nz * sizeof(float) ) ;
cudaMemcpy( dev_u, u, ny * nx * nz * sizeof(float), cudaMemcpyHostToDevice );
dim3 dimBlock(nx,ny,nz);
dim3 dimGrid(1,1);
FTCS3D<<<dimGrid, dimBlock>>>( dev_u );
cudaMemcpy( u, dev_u, ny * nx * nz * sizeof(float), cudaMemcpyDeviceToHost );

Inside the GPU: GPU内部:

__global__ void FTCS3D( float *u )
{
    int i = threadIdx.y+blockDim.y*blockIdx.y;
    int j = threadIdx.x+blockDim.x*blockIdx.x;
    int k = threadIdx.z+blockDim.z*blockIdx.z;
    int offset = i * nx + j + ny * nx * z;
    int totid=nx*ny*nz;

    if (offset < totid)
    {
        if ( offset ==1 )
           u[offset]=5.0;
   }
}

The number 5 appears in other matriz not in u[0][0][1], I do not have any idea about how to index all variables inside the offset remember I HAVE TO DO IT in this way of 1D vector.数字 5 出现在其他矩阵中而不是在 u[0][0][1] 中,我不知道如何索引偏移量内的所有变量,记住我必须以这种一维向量的方式来做。

If you have a array3D [HEIGHT][WIDTH] [DEPTH] then you could turn it into array1D [HEIGHT * WIDTH * DEPTH].如果你有一个 array3D [HEIGHT][WIDTH] [DEPTH] 那么你可以把它变成 array1D [HEIGHT * WIDTH * DEPTH]。

Out side your kernel you convert the 3D to 1D array在内核之外,您将 3D 数组转换为 1D 数组

for (int x = 0, k=0; x < HEIGHT; x++)
  for (int y = 0; y < WIDTH; y++)
     for (int z = 0; z < DEPTH; z++)
        a1D[k++] = a3D[x][y][z]

Why not only one dimension in you cuda?为什么在你的 cuda 中不只有一个维度?

__global__ void FTCS3D( float *u,int HEIGHT, int WIDTH, int DEPTH)
{   
    int x = threadIdx.x+blockDim.x*blockIdx.x;
    int totid = HEIGHT * WIDTH * DEPTH;

    if (x < totid)
    {
       if (x==1 )
          u[x]=5.0;
     }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM