2011-10-10 11 views
14

का उपयोग करके अधिकतम तत्व मान और उसकी स्थिति ढूँढना मैं न केवल मूल्य बल्कि अधिकतम (न्यूनतम) तत्व (res.val और res.pos) की स्थिति कैसे प्राप्त करूं?सीयूडीए थ्रस्ट

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_element (thrust::min_element) thrust/extrema.h में उपयोग करें: जब max_element को एक खाली सीमा गुजर

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; 

सावधान रहें - आप सुरक्षित रूप से परिणाम भिन्नता करने में सक्षम नहीं होगा।

5

जेरेड हॉबर्टॉक ने पहले ही इस प्रश्न का संतोषजनक उत्तर दिया है। मैं सामान्य मामले के लिए थोड़ा सा परिवर्तन प्रदान करना चाहता हूं जब सरणी को cudaMalloc द्वारा आवंटित किया गया है और device_vector कंटेनर के माध्यम से नहीं।

विचार एक device_pointermin_ptr को cudaMalloc 'एड कच्चे सूचक के चारों ओर एक device_pointerdev_ptr रैप करने के लिए, min_element के उत्पादन में कास्टिंग (मैं व्यापकता के किसी भी हानि के बिना अधिकतम करने के बजाय कम से कम पर विचार कर रहा हूँ) और फिर खोजने है 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]); 

} 
संबंधित मुद्दे