0

特定の CUDA 配列で最小の要素を見つけようとしています

float *p;
...    
thrust::device_ptr<float> pWrapper(p);    
thrust::device_ptr<float> pos = 
               thrust::min_element(pWrapper, pWrapper + MAXX * MAXY, thrust::minimum<float>());

pはリニア デバイス メモリで、pWrapperthrust::device_ptrです。

を使用するdevice_vectorと、最小要素の位置を簡単に見つけることができます

min_element(someDeviceVector) - someDeviceVector.begin()

それとは反対に、min_element呼び出しに指定された型が a のdevice_ptr場合、 の戻り値の型min_elementfloat *p(の定義されたテンプレートに従ってdevice_vector) です。提供したばかりのコード スニペットからは、最小値の場所がどこにあるのか、配列からそれを抽出する方法がわかりません。

min_element両方のアドレスの戻り値の型から減算しようとしましppWrapperが、どちらも機能しませんでした。

4

2 に答える 2

2

min_element の結果に * 演算子を使用するだけでよいことがわかりました。

于 2012-03-13T17:45:09.953 に答える
0

あなたの投稿では、cudaMalloc'ed 配列があり、その最小要素の位置と値を で見つけたいという非常に一般的なケースを検討していますthrust::min_element。以下に、他のユーザーに役立つことを願って、その完全な例を示します。

thrust::device_ptr基本的に、以下のソリューションは、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;
}
于 2014-11-05T22:10:47.320 に答える