2016-01-23 38 views
2

我是CUDA的初學者,並試圖找出最有效的方法來完成某件事。我有一個數組數組。我想要構建一個數組,它基本上是每個值出現在數組中的次數。有沒有一種使用CUDA的高效算法?如何從CUDA中的稀疏數組表示形式轉換爲密集形式表示形式

例如,我們假設值的範圍是0-10。實際上,我也有負面的價值觀,但我需要忽視這些。 (編輯:我已經嘗試過推力:: remove_if,然後是thrust :: reduce_by_key,但我正在尋找更有效率的方面,忽略了我不關心的元素,幾乎就像一個thrust :: reduce_by_key_if)。該列表遠遠小於值的範圍(即,絕大多數值超出了我所關心的範圍)。我可能有:

int32_t values[5] = {3, 5, 2, 5, 1, -1}; 

而且我想建立數組:

int32_t result[10] = {0, 1, 1, 1, 0, 2, 0, 0, 0, 0}; 

現在我在做它的CPU上居多。我嘗試過使用推力來對索引列表進行排序,以提高內存緩存性能,但性能改進最多隻能處於邊緣。

有什麼想法?有沒有一個優雅的方式來做到這一點?

+1

可能重複[計數在cuda數組中出現的數字](http://stackoverflow.com/questions/7573900/counting-occurences-of-numbers-in-cuda-array) –

+0

我試過但我不'我認爲這是最好的方法。我想忽略我不關心幫助提高績效的價值觀 – mathwiz

回答

0

推力::的remove_if其次是推力:: reduce_by_key最終成爲了我的應用程序的最佳方式。

2

您可以修改thrust histogram example只考慮排序構建直方圖時,非負值後:

#include <thrust/device_vector.h> 
#include <thrust/sort.h> 
#include <thrust/copy.h> 
#include <thrust/adjacent_difference.h> 
#include <thrust/iterator/counting_iterator.h> 
#include <thrust/find.h> 
#include <thrust/functional.h> 
#include <thrust/binary_search.h> 

#include <iostream> 
#include <iomanip> 
#include <iterator> 

#include <cstdint> 

template <typename Vector> 
void print_vector(const std::string& name, const Vector& v) 
{ 
    typedef typename Vector::value_type T; 
    std::cout << " " << std::setw(20) << name << " "; 
    thrust::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " ")); 
    std::cout << std::endl; 
} 

int main(void) 
{ 

    const std::int32_t N = 6; 

    std::int32_t values[6] = {3, 5, 2, 5, 1, -1}; 

    thrust::device_vector<std::int32_t> d_values(values, values + N); 

    print_vector("initial data", d_values); 

    // sort values to bring equal elements together 
    thrust::sort(d_values.begin(), d_values.end()); 

    print_vector("sorted data", d_values); 

    using thrust::placeholders::_1; 
    auto first_non_negative = thrust::find_if(d_values.begin(), d_values.end(), _1>=0); 

    // number of histogram bins is equal to the maximum value plus one 
    std::int32_t num_bins = d_values.back() + 1; 

    thrust::device_vector<std::int32_t> histogram(num_bins); 

    thrust::counting_iterator<std::int32_t> search_begin(0); 
    thrust::upper_bound(first_non_negative, d_values.end(), 
         search_begin, search_begin + num_bins, 
         histogram.begin()); 

    thrust::adjacent_difference(histogram.begin(), histogram.end(), 
           histogram.begin()); 

    print_vector("histogram", histogram); 

    return 0; 
} 

輸出

initial data 3 5 2 5 1 -1 
sorted data -1 1 2 3 5 5 
histogram  0 1 1 1 0 2 
相關問題