求cuda中n点之间的最小距离

求cuda中n点之间的最小距离,cuda,shared-memory,minimum,Cuda,Shared Memory,Minimum,我试图找到cuda中n个点之间的最小距离。我写了下面的代码。这对于从1到1024的点数(即1个块)来说效果良好。但若num_points大于1024,我得到的最小距离值是错误的。我正在使用蛮力算法检查gpu最小值和在CPU中找到的值。 最小值存储在内核函数末尾的temp1[0]中 我不知道这是怎么回事。请帮帮我 #include <stdio.h> #include <stdlib.h> #include <math.h> #include <sys/t

我试图找到cuda中n个点之间的最小距离。我写了下面的代码。这对于从1到1024的点数(即1个块)来说效果良好。但若num_points大于1024,我得到的最小距离值是错误的。我正在使用蛮力算法检查gpu最小值和在CPU中找到的值。 最小值存储在内核函数末尾的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);
.
.

我想说的是你选择的算法有问题。你当然可以在^2上做得更好,即使你的操作非常简单。当然,在5000点上,这看起来并不可怕,但是尝试50000点,你会感到痛苦


我会考虑并行化一个或类似结构的构造,它可能更容易查询,代码差异更小。

我没有检查您的代码的一致性,我也不想回答您的问题。作为评论,使用两个内核是否会更高效、更少出错,一个简单易用,并行计算点之间所有可能的距离,一个执行缩减操作。您可以使用CUDA样本中提供的算法之一,或使用由此获得的距离矩阵的推力库?现在我只是尝试并行化程序,不必担心关于复杂性。上面的代码给出了超过1个块的错误值。你能说出那个实现中的错误吗?我认为这并不能回答海报的调试问题。