Created
December 6, 2015 07:18
-
-
Save cive/96cfb3007632bb532f19 to your computer and use it in GitHub Desktop.
curandsampleにコメントを付けた
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * sample code | |
| * from http://d.hatena.ne.jp/fjnl/20101127/1290880661 | |
| * comment by cive | |
| */ | |
| #include <iostream> | |
| #include <iterator> | |
| #include <curand.h> | |
| // http://stackoverflow.com/questions/11734578/curand-library-compiling-error-undefined-reference-to-functions | |
| // nvcc -L/path/to/cuda/libs -o curandsample.exe curandsample.cu -lcurand | |
| int main() { | |
| // 疑似乱数生成 | |
| curandGenerator_t g; | |
| // ernel終了実行待ちのCPU使用率削減とかできるらしい。(引数は1つらしい) kwsk => | |
| // http://topsecret.hpc.co.jp/wiki/index.php/CPU%E4%BD%BF%E7%94%A8%E7%8E%87%E3%82%92%E6%8A%91%E3%81%88%E3%81%9FCUDA%E5%AE%9F%E8%A1%8C | |
| // http://docs.nvidia.com/cuda/cuda-runtime-api/index.html#group__CUDART__DEVICE_1g18074e885b4d89f5a0fe1beab589e0c8 | |
| // Mapped MemoryはCUDA 2.2から導入された新機能です。 今までのCUDAプログラミングにおいては、Host Memory(ホストマシン上のメインメモリ)と Device Memory(GPU上のビデオメモリ)はまったく別個のアドレス空間上のメモリとして明確に分けられていました。 しかし、Mapped Memoryを使用することによって、これらの違いを明確に区別せずCUDAプログラミングを行うことができるようになります。 | |
| // quad http://gpu.fixstars.com/index.php/MappedMemory%E3%82%92%E4%BD%BF%E3%81%86 | |
| cudaSetDeviceFlags(cudaDeviceMapHost); | |
| // 初期化 | |
| curandCreateGenerator(&g, CURAND_RNG_PSEUDO_DEFAULT); | |
| // Seed設定 | |
| curandSetPseudoRandomGeneratorSeed(g, 0); | |
| // 100個の乱数を同時生成 | |
| int const n = 100; | |
| float* p; | |
| float* dp; | |
| // http://d.hatena.ne.jp/fjnl/20101127/1290880661 | |
| // CPU側のメモリを確保 | |
| // http://www.slis.tsukuba.ac.jp/~fujisawa.makoto.fu/cgi-bin/wiki/index.php?%A5%DA%A1%BC%A5%B8%A5%ED%A5%C3%A5%AF%A5%DB%A5%B9%A5%C8%A5%E1%A5%E2%A5%EA | |
| // cudaHostAllocMapped … デバイスのアドレス空間にPage-lockedホストメモリブロックをマップする. そのため,このブロックは2つのアドレス(ホストとデバイス)を持つ.ホスト側のアドレスはcudaHostAllocの引数ptrで返され, デバイス側はcudaHostGetDevicePointer()で取得することができる. | |
| cudaHostAlloc(&p, n * sizeof(float), cudaHostAllocMapped); | |
| cudaHostGetDevicePointer(&dp, p, 0); | |
| // 一様分布で乱数生成 | |
| curandGenerateUniform(g, dp, n); | |
| // http://render.s73.xrea.com/project/2009/01/cuda4cuda.html | |
| // cudaThreadSynchronize()で、前のCUDA呼び出しがすべて終わるまで処理をストップ | |
| cudaThreadSynchronize(); | |
| // std::copyを使って標準出力 | |
| std::copy(p, p + n, std::ostream_iterator<float>(std::cout, "\n")); | |
| // curandで使用したメモリを解放 | |
| curandDestroyGenerator(g); | |
| // cudaで使用したCPU側のメモリを解放 | |
| cudaFreeHost(p); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment