这是执行您打算执行的操作的代码,即使它可能不是最佳的:
// Compiled using nvcc main.cu -arch=sm_21 -o main && ./main
// See document http://www.cs.cmu.edu/afs/cs/academic/class/15668-s11/www/cuda-doc/CURAND_Library.pdf
// And http://aresio.blogspot.fr/2011/05/cuda-random-numbers-inside-kernels.html
#include <stdio.h>
#include <cuda.h>
#include <curand_kernel.h>
#include <curand.h>
#define cuda_DBG(x) if(x!=cudaSuccess) {\
printf("error at %s:%u\n", __FILE__, __LINE__);\
return -1;\
}
__global__ void setup_kernel(curandState *state, unsigned long seed ) {
int id = threadIdx.x;
curand_init( seed, id, 0, &state[id] );
}
__global__ void generateVector(int *hData, curandState *globalState) {
size_t i = blockIdx.x;
float RANDOM = 100*curand_uniform( &globalState[i] );
hData[i] = (int)RANDOM;
if(i==50) printf("hData[50]=%u (RANDOM=%f)\n", hData[i], RANDOM);
}
int main() {
int *A = NULL, numOfData=1000;
curandState *devState;
cuda_DBG(cudaMalloc((void **) &A, sizeof(int)*numOfData));
cuda_DBG(cudaMalloc((void **) &devState, sizeof(devState)*numOfData));
setup_kernel<<<numOfData, 1>>>(devState, time(NULL));
generateVector<<<numOfData, 1>>>(A, devState);
cuda_DBG(cudaFree(A));
cuda_DBG(cudaFree(devState));
}