在您的帖子中,您正在考虑非常常见的情况,即您有一个cudaMalloc
'ed 数组并且您想通过thrust::min_element
. 下面,我提供了一个完整的例子,希望它对其他用户有用。
thrust::device_ptr
基本上,下面的解决方案共享将 a 包裹在cudaMalloc
'ed 线性内存周围的相同想法。但是,该位置是由 找到的thrust::distance
。
这是完整的代码:
#include <thrust/device_vector.h>
#include <thrust/extrema.h>
/********************/
/* CUDA ERROR CHECK */
/********************/
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, 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() {
const int N = 16;
srand(time(NULL));
// --- Host side memory allocation and initialization
float *h_A = (float*)malloc(N * sizeof(float));
for (int i=0; i<N; i++) h_A[i] = rand();
// --- Device side memory allocation and initialization
float *d_A; gpuErrchk(cudaMalloc((void**)&d_A, N * sizeof(float)));
gpuErrchk(cudaMemcpy(d_A, h_A, N * sizeof(float), cudaMemcpyHostToDevice));
thrust::device_ptr<float> dp = thrust::device_pointer_cast(d_A);
thrust::device_ptr<float> pos = thrust::min_element(dp, dp + N);
unsigned int pos_index = thrust::distance(dp, pos);
float min_val;
gpuErrchk(cudaMemcpy(&min_val, &d_A[pos_index], sizeof(float), cudaMemcpyDeviceToHost));
for (int i=0; i<N; i++) printf("d_A[%i] = %f\n", i, h_A[i]);
printf("\n");
printf("Position of the minimum element = %i; Value of the minimum element = %f\n", thrust::distance(dp, pos), min_val);
cudaDeviceReset();
return 0;
}