15

如何不仅获取值,还获取最大(最小)元素(res.valres.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>());
4

2 回答 2

18

不要使用thrust::reduce. 在 中使用thrust::max_element( thrust::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——您将无法安全地取消引用结果。

于 2011-10-10T07:24:54.287 回答
6

Jared Hoberock 已经令人满意地回答了这个问题。我想在下面提供一个细微的更改,以说明当数组是由容器分配cudaMalloc而不是通过device_vector容器分配时的常见情况。

这个想法是将 a 包裹device_pointer dev_ptrcudaMalloc'ed 原始指针周围,将min_element(我正在考虑最小值而不是最大值而不失一般性)的输出转换为 a device_pointer min_ptr,然后找到最小值 asmin_ptr[0]和位置 by &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]);

}
于 2015-02-18T22:27:38.983 回答