Merge topic 'cmake-pkg-config-integration'
[kiteware-cmake.git] / Tests / CudaOnly / SharedRuntimePlusToolkit / curand.cu
blobfdd7b53230c64ad19ae5558f9cdab1737efbba25
1 // Comes from:
2 // https://docs.nvidia.com/cuda/curand/host-api-overview.html#host-api-example
4 #ifdef _WIN32
5 #  define EXPORT __declspec(dllexport)
6 #else
7 #  define EXPORT
8 #endif
11  * This program uses the host CURAND API to generate 100
12  * pseudorandom floats.
13  */
14 #include <cuda.h>
15 #include <curand.h>
16 #include <stdio.h>
17 #include <stdlib.h>
19 #define CUDA_CALL(x)                                                          \
20   do {                                                                        \
21     if ((x) != cudaSuccess) {                                                 \
22       printf("Error at %s:%d\n", __FILE__, __LINE__);                         \
23       return EXIT_FAILURE;                                                    \
24     }                                                                         \
25   } while (0)
26 #define CURAND_CALL(x)                                                        \
27   do {                                                                        \
28     if ((x) != CURAND_STATUS_SUCCESS) {                                       \
29       printf("Error at %s:%d\n", __FILE__, __LINE__);                         \
30       return EXIT_FAILURE;                                                    \
31     }                                                                         \
32   } while (0)
34 EXPORT int curand_main()
36   size_t n = 100;
37   size_t i;
38   curandGenerator_t gen;
39   float *devData, *hostData;
41   /* Allocate n floats on host */
42   hostData = (float*)calloc(n, sizeof(float));
44   /* Allocate n floats on device */
45   CUDA_CALL(cudaMalloc((void**)&devData, n * sizeof(float)));
47   /* Create pseudo-random number generator */
48   CURAND_CALL(curandCreateGenerator(&gen, CURAND_RNG_PSEUDO_DEFAULT));
50   /* Set seed */
51   CURAND_CALL(curandSetPseudoRandomGeneratorSeed(gen, 1234ULL));
53   /* Generate n floats on device */
54   CURAND_CALL(curandGenerateUniform(gen, devData, n));
56   /* Copy device memory to host */
57   CUDA_CALL(
58     cudaMemcpy(hostData, devData, n * sizeof(float), cudaMemcpyDeviceToHost));
60   /* Cleanup */
61   CURAND_CALL(curandDestroyGenerator(gen));
62   CUDA_CALL(cudaFree(devData));
63   free(hostData);
64   return EXIT_SUCCESS;