curand.cpp 2.0 KB

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