【问题标题】:Adding all combinations of array elements using GPU [closed]使用 GPU 添加数组元素的所有组合 [关闭]
【发布时间】:2016-03-14 13:17:32
【问题描述】:

我是 CUDAfy 编程的新手,在计算数组中所有元素组合的总和时遇到了麻烦。我似乎想不出适合移植到 GPU 上的算法。 非常感谢任何帮助或任何类型的算法。

序列版代码如下:

for (int i = 0; i < Array.Count - 1; i++)
{
    for (int j = (i + 1); j < Array.Count; j++)
    {
         ans.Add(Array.ElementAt(i) + Array.ElementAt(j));     

    }
}

【问题讨论】:

  • 事实上,我遇到了类似的问题。我对此也很陌生。我相信可以将数组的元素存储在两个不同的数组中,这种方式可以直接将两个元素逐个元素相加,从而获得所需的结果。但首先需要相当多的指令和比较才能获得这些数组,并且可能不是最好的方法。希望这会有所帮助...

标签: c# cuda parallel-processing gpu cudafy.net


【解决方案1】:

这并没有给 GPU 提供很多工作,除了一次添加。在您看到好处之前,该数组必须相当大。无论如何:

我使用 C++,不熟悉 C# 或 CUDAfy,但应该很容易移植逻辑。将每对元素之和存储在数组中的核函数是:

template<typename T>
__global__ void sum_combinations_of_array( const T* arr, const size_t len, T* dest )
{
    const int tx = blockIdx.x*blockDim.x+threadIdx.x;
    const int ty = blockIdx.y*blockDim.y+threadIdx.y;
    if( tx < len && ty < len && tx < ty ) {
        dest[tx*len+ty] = arr[tx]+arr[ty];
    }
}

您只是使用 2D 线程块来决定要添加数组的哪些元素(它们只是在您的代码中代替 ij)。 arr 的大小应至少为 lendest 的大小应至少为 len*len。设置所有这些并运行它的主机代码将类似于:

const int len = 1000;

int* arr;
cudaMalloc( &arr, len*sizeof(int) );

int* matrix;
cudaMalloc( &matrix, len*len*sizeof(int) );
// cudaMalloc2D could also be used here, but then you'll
// have to pay attention to the pitch
cudaMemset( matrix, 0, len*len*sizeof(int) );

// copy host array to arr with cudaMemcpy
// ...

const int numThreads = ???; // depends on your hardware
dim3 grid( len, (len+numThreads-1)/numThreads ), threads( 1, numThreads );
sum_combinations_of_array<int><<<grid,threads>>>( arr, len, matrix );
cudaDeviceSynchronize(); // wait for completion

// copy device matrix to host with cudaMemcpy (or cudaMemcpy2D)
// remember any element i<=j will be 0
// ...

cudaFree( arr );
cudaFree( matrix );

【讨论】:

    猜你喜欢
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2012-09-22
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2017-07-10
    相关资源
    最近更新 更多