Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

Cuda: Compact and result size

I am attempting to use CUDA to find the distance between objects with 3D coordinates. That said, I am only interested in 2 types of objects. The objects are represented as numbers in an array. For this question I am only interested in getting the positions of the first type of object (a user specified number) in the object array.

To that end I'm currently trying to pass this list and a results list to my device and have the device check if each location in the array is the specified number (representing the first object) - and if it is, place that array location in a results array to be returned to the host.

As an example input, suppose I have:

int objectArray[10] = { 1, 11, 7, 2, 7, 23, 6, 6, 9, 11 };

int results[10]={0,0,0,0,0,0,0,0,0,0};

and I'm trying to get the positions of all the instances of 7 (and preferably, a returned value stating how many instances of 7 were found) ie. (with instances of 7 being present in position 2 and 4 of objectArray)

results={2,4,0,0,0,0,0,0,0,0};

resultCount=2;

I'm fairly new to Cuda and if anyone knows how this is done, I'd appreciate the help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this using thrust as @RobertCrovella already pointed out. The following example uses thrust::copy_if to copy all of elements' indices for which the condition ("equals 7") is fulfilled. thrust::counting_iterator is used to avoid creating the sequence of indices explicitly.

#include <thrust/copy.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/functional.h>
#include <iostream>

using namespace thrust::placeholders;

int main()
{
    const int N = 10;
    int objectArray[N] = { 1, 11, 7, 2, 7, 23, 6, 6, 9, 11 };
    int results[N]={0};

    int* end = thrust::copy_if(thrust::make_counting_iterator(0), thrust::make_counting_iterator(N), objectArray, results, _1 == 7);

    thrust::copy(results, results+N, std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl << "result count = " << end-results << std::endl;
    return 0;
}

Output:

2 4 0 0 0 0 0 0 0 0
result count = 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...