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

CUDA::基本::並列処理2

問題1


float型のデータ100個を用意し、それをGPU上で100加える処理を行え。

その他条件:
 ブロック数:1×1×1
 スレッド数:100×1×1

答え

//main.cu
#include <iostream>
#include <algorithm>
#include <cutil.h>

const int AryElem = 100; //要素数

//-----------各種プロトタイプ宣言----------//
__global__ void GpuFunction(float *input);

//------------ここからメイン関数---------//
int main(int argc, char **argv)
{

	CUT_DEVICE_INIT(argc,argv); //初期化

	
	float* x = new float[AryElem]; //float型をAryElem個
	for( int i = 0; i < AryElem; ++i){
		x[i] = static_cast<float>(i); //適当に初期化
	}


	//---GPU用にメモリ確保---//
	float* gpu_x;
	int DataSize = sizeof(float) * AryElem;
	CUDA_SAFE_CALL(cudaMalloc( reinterpret_cast<void**>( &gpu_x), DataSize) );

	//GPUへデータをコピー(Host -> GPU)
	CUDA_SAFE_CALL( cudaMemcpy( gpu_x, x, DataSize , cudaMemcpyHostToDevice));
	
	
	//GPU用にブロックとスレッドを用意
	dim3 threads(AryElem,1,1); //スレッドAryElem個
	dim3 grid(1,1,1); //Dg は 1;

	//GPUでの計算
	GpuFunction<<<grid,threads>>>(gpu_x);

	//GPUから戻す(GPU -> Host)
	CUDA_SAFE_CALL( cudaMemcpy( x, gpu_x,DataSize, cudaMemcpyDeviceToHost) );
	cudaFree(gpu_x); //メモリ解放


	//結果を出力
	std::copy(x,x+AryElem,std::ostream_iterator<float>(std::cout ,"\n"));
	delete[] x;

	CUT_EXIT(argc, argv);//終了

	return 0;
}

//----------- ここからGPU上の計算 --------------------//
__global__ void GpuFunction(float *input)
{
	input[threadIdx.x] += 100;
	__syncthreads(); //同期をとる
}


問題2


問題1を以下の条件に変更して同じ結果になるようにせよ。

その他条件:
 ブロック数:1×1×1
 スレッド数:10×10×1

答え

#include <algorithm>
#include <cutil.h>

const int AryElem = 100; //要素数

//-----------各種プロトタイプ宣言----------//
__global__ void GpuFunction(float *input);

//------------ここからメイン関数---------//
int main(int argc, char **argv)
{

	CUT_DEVICE_INIT(argc,argv); //初期化

	
	float* x = new float[AryElem]; //float型をAryElem個
	for( int i = 0; i < AryElem; ++i){
		x[i] = static_cast<float>(i); //適当に初期化
	}


	//---GPU用にメモリ確保---//
	float* gpu_x;
	int DataSize = sizeof(float) * AryElem;
	CUDA_SAFE_CALL(cudaMalloc( reinterpret_cast<void**>( &gpu_x), DataSize) );

	//GPUへデータをコピー(Host -> GPU)
	CUDA_SAFE_CALL( cudaMemcpy( gpu_x, x, DataSize , cudaMemcpyHostToDevice));
	
	
	//GPU用にブロックとスレッドを用意
	dim3 threads(10,10,1); //スレッド10 *10 = AryElem個
	dim3 grid(1,1,1); //Dg は 1;

	//GPUでの計算
	GpuFunction<<<grid,threads>>>(gpu_x);

	//GPUから戻す(GPU -> Host)
	CUDA_SAFE_CALL( cudaMemcpy( x, gpu_x,DataSize, cudaMemcpyDeviceToHost) );
	cudaFree(gpu_x); //メモリ解放


	//結果を出力
	std::copy(x,x+AryElem,std::ostream_iterator<float>(std::cout ,"\n"));
	delete[] x;

	CUT_EXIT(argc, argv);//終了

	return 0;
}

//----------- ここからGPU上の計算 --------------------//
__global__ void GpuFunction(float *input)
{
	const int TidX = threadIdx.x;
	const int TidY = threadIdx.y;
	const int BidX = blockDim.x; //ブロックの幅
	input[TidY*BidX+TidX] += 100;
	__syncthreads(); //同期をとる
}

メモ


dim3型は(x,y,z)の3要素をもつ。

スレッドのID(インデックス)を拾うには、「threadIdx.x」などを使う。
ブロック幅は「blockDim.x」でひろえる。

目次

― その他 ―

Wiki内検索

計測中...(07.10.8〜)

Save The World






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


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

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