最終更新: mikk_ni3_92 2008年04月15日(火) 18:20:19履歴
現在地 >> メニュー >> CUDA >> CUDA::基本::並列処理
→ CUDA::基本::並列処理2
→ CUDA::基本::並列処理2
//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(); //同期をとる }
#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(); //同期をとる }