推力/ CUDA将一个数组与另一个数组的值组合多次复制

时间:2018-11-14 08:47:49

标签: cuda thrust

假设我有两个数组

A = {1, 2, 3}

B = {10,20,30,40,50}

我想生成一个新的数组,其大小为

sizeof(A) * sizeof(B)

我想复制B sizeof(A)次,并且在每次重复i上,结果数组都应添加A[i]。因此结果将是类似

{11,21,31,41,51,12,22,32,42,52,13,23,33,43,53}

1 个答案:

答案 0 :(得分:3)

此任务可以解释为二维问题,其中输出数组可以视为维度sizeof(A)乘以sizeof(B)的矩阵。这样,我们可以使用2D CUDA索引来实现所需的功能。此2D实现的示例CUDA C ++代码如下所示:

#include <iostream>
#include <cuda_runtime.h>
#include <cassert>

using namespace std;

__global__ void kernel_replicate(int* a, int* b, int* c, int alen, int blen, int clen)
{
    const int ai = blockIdx.x * blockDim.x + threadIdx.x;
    const int bi = blockIdx.y * blockDim.y + threadIdx.y;

    if(ai<alen && bi<blen)
    {
        const int ci = ai * blen + bi;
        c[ci] = a[ai] + b[bi];
    }
}


void replicate_device(int* a, int* b, int* c, int alen, int blen, int clen)
{
    dim3 block(16,16);
    dim3 grid;
    grid.x = (alen + block.x - 1) / block.x;
    grid.y = (blen + block.y - 1) / block.y;

    kernel_replicate<<<grid, block>>>(a,b,c,alen,blen,clen);

    assert(cudaSuccess == cudaDeviceSynchronize());
}


void replicate(int* a, int* b, int* c, int alen, int blen, int clen)
{
    int *ad, *bd, *cd;

    size_t abytes = alen * sizeof(int);
    size_t bbytes = blen * sizeof(int);
    size_t cbytes = clen * sizeof(int);

    cudaMalloc(&ad, abytes);
    cudaMalloc(&bd, bbytes);
    cudaMalloc(&cd, cbytes);

    cudaMemcpy(ad,a, abytes, cudaMemcpyHostToDevice);
    cudaMemcpy(bd,b, bbytes, cudaMemcpyHostToDevice);

    replicate_device(ad,bd,cd, alen,blen,clen);

    cudaMemcpy(c,cd, cbytes, cudaMemcpyDeviceToHost);


    cudaFree(ad);
    cudaFree(bd);
    cudaFree(cd);
}


int main()
{
    const int alen = 3;
    const int blen = 5;
    const int clen = alen * blen;

    int A[alen] = {1,2,3};
    int B[blen] = {10,20,30,40,50};
    int C[clen] = {0};

    replicate(A,B,C,alen, blen, clen);

    for(int i=0; i<alen; i++)
    {
        cout<<A[i]<<" ";
    }
    cout<<endl;

    for(int i=0; i<blen; i++)
    {
        cout<<B[i]<<" ";
    }
    cout<<endl;

    for(int i=0; i<clen; i++)
    {
        cout<<C[i]<<" ";
    }
    cout<<endl;


    return 0;
}