2011-10-10 470 views
14

如何獲取最大(最小)元素(res.valres.pos)的值以及位置?使用CUDA Thrust查找最大元素值及其位置

thrust::host_vector<float> h_vec(100); 
thrust::generate(h_vec.begin(), h_vec.end(), rand); 
thrust::device_vector<float> d_vec = h_vec; 

T res = -1; 
res = thrust::reduce(d_vec.begin(), d_vec.end(), res, thrust::maximum<T>()); 

回答

17

請勿使用thrust::reduce。使用thrust::max_elementthrust::min_element)在thrust/extrema.h

thrust::host_vector<float> h_vec(100); 
thrust::generate(h_vec.begin(), h_vec.end(), rand); 
thrust::device_vector<float> d_vec = h_vec; 

thrust::device_vector<float>::iterator iter = 
    thrust::max_element(d_vec.begin(), d_vec.end()); 

unsigned int position = iter - d_vec.begin(); 
float max_val = *iter; 

std::cout << "The maximum value is " << max_val << " at position " << position << std::endl; 

傳遞一個空範圍max_element時要小心 - 你將不能夠安全地引用這些結果。

5

Jared Hoberock已經圓滿地回答了這個問題。我想在下面略微改動一下,以解釋當數組已被cudaMalloc分配而不是通過device_vector容器分配的常見情況。

的想法是緊裹device_pointerdev_ptrcudaMalloc「編原始指針周圍,鑄件的min_element輸出(我考慮最小的,而不是沒有任何一般性損失的最大值)到device_pointermin_ptr和然後找到最小值爲min_ptr[0],位置爲&min_ptr[0] - &dev_ptr[0]

#include "cuda_runtime.h" 
#include "device_launch_paraMeters.h" 

#include <thrust\device_vector.h> 
#include <thrust/extrema.h> 

/***********************/ 
/* CUDA ERROR CHECKING */ 
/***********************/ 
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); } 
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true) 
{ 
    if (code != cudaSuccess) 
    { 
     fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line); 
     if (abort) exit(code); 
    } 
} 

/********/ 
/* MAIN */ 
/********/ 
int main() { 

    srand(time(NULL)); 

    const int N = 10; 

    float *h_vec = (float *)malloc(N * sizeof(float)); 
    for (int i=0; i<N; i++) { 
     h_vec[i] = rand()/(float)(RAND_MAX); 
     printf("h_vec[%i] = %f\n", i, h_vec[i]); 
    } 

    float *d_vec; gpuErrchk(cudaMalloc((void**)&d_vec, N * sizeof(float))); 
    gpuErrchk(cudaMemcpy(d_vec, h_vec, N * sizeof(float), cudaMemcpyHostToDevice)); 

    thrust::device_ptr<float> dev_ptr = thrust::device_pointer_cast(d_vec); 

    thrust::device_ptr<float> min_ptr = thrust::min_element(dev_ptr, dev_ptr + N); 

    float min_value = min_ptr[0]; 
    printf("\nMininum value = %f\n", min_value); 
    printf("Position = %i\n", &min_ptr[0] - &dev_ptr[0]); 

}