【问题标题】:Finding minimum distance between n points in cuda找到cuda中n点之间的最小距离
【发布时间】:2013-12-09 06:04:36
【问题描述】:

我试图找到 cuda 中 n 个点之间的最小距离。我写了下面的代码。这适用于从 1 到 1024 的点数,即 1 个块。但是如果 num_points 大于 1024,我得到的最小距离值是错误的。我正在使用蛮力算法在 CPU 中找到的值检查 gpu 最小值。 最小值存储在内核函数末尾的 temp1[0] 中。

我不知道这有什么问题。请帮帮我..

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/time.h>
#define MAX_POINTS 50000

__global__ void minimum_distance(float * X, float * Y, float * D, int n) {

__shared__ float temp[1024];
float temp1[1024];
int tid = threadIdx.x;
int bid = blockIdx.x;
int ref = tid+bid*blockDim.x;
temp[ref] = 1E+37F;
temp1[bid] = 1E+37F;
float dx,dy;
float Dij;
int i;

            //each thread will take a point and find min dist to all
            // points greater than its unique id(ref)
    for (i = ref + 1; i < n; i++) 
    {
        dx = X[ref]-X[i];
        dy = Y[ref]-Y[i];
        Dij = sqrtf(dx*dx+dy*dy);
        if (temp[tid] > Dij)
        {
         temp[tid] = Dij;
        }
    }   

    __syncthreads();

            //In each block the min value is stored in temp[0]
    if(tid == 0)
    {
        if( bid == (n-1)/1024 ) {
        int end = n - (bid) * 1024;
        for (i = 1; i < end; i++ )   
        {
            if (temp[i] < temp[tid])
            temp[tid] = temp[i];
        }
        temp1[bid] = temp[tid];
        }
        else {
        for (i = 1; i < 1024; i++ )   
        {
            if (temp[i] < temp[tid])
            temp[tid] = temp[i];
        }
        temp1[bid] = temp[tid];
        }   
    }

__syncthreads();

    //Here the min value is stored in temp1[0]
if (ref == 0)
{
    for (i = 1; i <= (n-1)/1024; i++)
        if( temp1[bid] > temp1[i])
            temp1[bid] = temp1[i];

    *D=temp1[bid];
}
}

//part of Main function 
//kernel function invocation
// Invoking kernel of 1D grid and block sizes  
// Vx and Vy are arrays of x-coordinates and y-coordinates respectively  

int main(int argc, char* argv[]) {
.
.
blocks = (num_points-1)/1024 + 1;
minimum_distance<<<blocks,1024>>>(Vx,Vy,dmin_dist,num_points);
.
.

【问题讨论】:

  • 我没有检查你的代码的一致性,我也不想回答你的问题。就像评论一样,使用两个内核会更有效且更不容易出错,一个可以直接实现并并行计算点之间的所有可能距离,另一个执行归约操作(您可以使用其中一种算法CUDA 样本中提供或使用推力库) 的如此获得的距离矩阵?

标签: cuda shared-memory minimum


【解决方案1】:

我想说的是你选择的算法有什么问题。你当然可以比 O(n^2) 做得更好——即使你的很简单。当然,在 5,000 点上它可能看起来并不可怕,但尝试 50,000 点,你会感到痛苦......

我会考虑并行化 Voronoi Diagram 的构造,或者可能是某种类似 BSP 的结构,这样可能更容易查询且代码差异较小。

【讨论】:

  • 现在我只是尝试并行化程序,而不是担心复杂性。上面的代码给了我超过 1 个块的错误值。你能说一下这个实现有什么问题吗?
  • 我不认为这回答了发帖者的调试问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 2016-02-19
  • 1970-01-01
相关资源
最近更新 更多