curand.cpp 2.1 KB

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