如何删除带有CUDA Thrust的嵌套循环以进行全对距离检查?

时间:2017-04-24 08:51:51

标签: c++ loops cuda nested thrust

我有两个数组 array1 array2 分别带有 n m 元素。我想找到元素之间的所有对距离。然后在CPU上使用强力算法:

for(int i =0; i<n; i++)
{
    for(int j =0; j<m; j++)
    {
         array_pair_distances[i][j] = array1[i]-array2[j];
    }       
}

使用CUDA Thrust我通过使用thrust :: transform和单个for循环简单地将这个 n * m 问题转化为n或m问题。我的问题是如何使用Thrust删除最后一个for循环?

编辑:添加了Thrust和一个for循环的实现示例。代码检查对距离是否大于0.1并返回int。

#include <stdio.h>
#include <iostream>
#include <cuda.h>

#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/random.h>
#include <thrust/fill.h>
#include <thrust/transform.h>
#include <thrust/reduce.h>

struct PairDistanceCheck : public thrust::binary_function<float,float,int>
{
    __host__ __device__
        int operator()(const float& a, const float& b) const
        {
           if(thrust::get<0>(a) - thrust::get<0>(b) > 0.1)
           {
                return 1;
           } 
           else return 0;
        }
};

void function()
{
    int n = 1000;
    int m = 2000;

    // Initialization of host vectors 
    thrust::host_vector<float> h_1 (n);
    thrust::host_vector<float> h_2 (m);

    // Fill host_vectors with data
    *
    *
    *
    //

    // Copy host_vectors to device_vectors
    thrust::device_vector<float> d_1 = h_1;
    thrust::device_vector<float> d_2 = h_2;

    thrust::device_vector<float> d_temp (m);

    thrust::device_vector<int> d_sum (m);
    thrust::fill(d_sum.begin(), d_sum.end(), 0);

    thrust::device_vector<int> d_result (m);

    for (int i=0; i<n; i++)
    {
        // Filling device_vector d_temp with element i from d_2
        thrust::fill(d_temp.begin(), d_temp.end(), d_2[i]);

        thrust::transform((d_1.begin(), d_1.end(), d_temp.begin(), d_result.begin(), PairDistanceCheck());

        // Summing the vectors
        thrust::transform(d_sum.begin(), d_sum.end(), d_result.begin(), d_sum.begin(), thrust::plus<int>());

    }

    // Final sum
    int sum = thrust::reduce(d_sum.begin(), d_sum.end(), (int) 0, thrust::plus<int>());

    return 0;
}

1 个答案:

答案 0 :(得分:1)

答案非常简短,你做不到。

Thrust没有外部产品算法,这是执行您感兴趣的计算所需的算法。您可以通过填充两个矩阵的行/列来完成此操作输入向量然后直接减去那些。但与适当的外部产品实现相比,这将是非常低效的(内存和性能)。