現在地 >> メニュー >> CUDA >> CUDA::基本::並列処理 >> CUDA::基本::並列処理2 >> CUDA::基本::並列処理3

問題


以下のデータ構造をGPUに引数として渡して、何らかの処理を行え。

typedef struct
{
float Re;
float Im;
}COMPLEX;

答え : 初期値を設定し、GPU上でそれぞれ10000を加える


#include <iostream>
#include <string>
#include <cuda_runtime.h>

using namespace std;


typedef struct
{
float Re;
float Im;
}COMPLEX;


/********[エラー処理]********/
namespace
{
void errorexit(string message)
{
cerr << message << endl;
exit(1);
}

}

/************************************************************************/
/* ここから「G」PUでの処理 */
/************************************************************************/
__global__ void ADD_REAL(COMPLEX *o_data,float value)
{
const int tid = threadIdx.x; //スレッドのId(x座標)取得
o_data[tid].Re += value ;
o_data[tid].Im += value ;

}





/*****************************************************************/
/* ここから 「C」PU での処理 */
/****************************************************************/

/**********************[CUDAの初期化]*********************/
void InitCUDA(void)
{
int count = 0;
int i = 0;
cudaGetDeviceCount(&count);
if(count == 0) {
errorexit("There is no device");
}

for( i = 0; i < count; i++) {
cudaDeviceProp prop;
if(cudaGetDeviceProperties(& prop, i) == cudaSuccess) {
if(prop.major >= 1) {
break;
}
}
}

if(i == count)
{
errorexit( "There is no device supporting CUDA 1.x.");
}
cudaSetDevice(i);
}


/******************** [メイン関数] *************************/
int main(int argc, char** argv)
{

InitCUDA();

COMPLEX *c = new COMPLEX[100];

for(int i = 0; i < 100;++i)
{
c[i].Re = static_cast<float>(i);
c[i].Im = static_cast<float>(i*i);
}

COMPLEX* gpu_c = NULL; //GPU
cudaMalloc( reinterpret_cast<void**>( &gpu_c), sizeof(COMPLEX) * 100);
if(gpu_c == NULL)
{
errorexit("can't cudaMalloc");
}

cudaMemcpy( gpu_c, c, sizeof(COMPLEX) * 100 , cudaMemcpyHostToDevice);


dim3 block(1,1,1);//ブロック1個
dim3 threads(100,1,1); //スレッド100個

ADD_REAL<<<block, threads,0>>>(gpu_c,10000);
cudaThreadSynchronize();


/* GPU => CPUへコピー */
cudaMemcpy( c, gpu_c, sizeof(COMPLEX) * 100, cudaMemcpyDeviceToHost);
cudaFree(gpu_c); gpu_c = NULL;

/* 出力 */
for( int i = 0; i < 100; i++)
{
cout << c[i].Re << " , " << c[i].Im << "\n";
}

delete [] c;c=NULL;

return 0;
}

メモ


CUDA_VS2005_Wizardから作成した。(コンパイルにC++のオプション設定が必要)

目次

― その他 ―

Wiki内検索

計測中...(07.10.8〜)

Save The World






▲よろしければ広告のクリックもお願いします


▲ランキングに参加しました

管理人/副管理人のみ編集できます