1+ #include < particle.h>
2+ #include < stdlib.h>
3+ #include < stdio.h>
4+
5+ __global__ void advanceParticles (float dt, particle * pArray, int nParticles)
6+ {
7+ int idx = threadIdx.x + blockIdx.x *blockDim.x ;
8+ if (idx < nParticles)
9+ {
10+ pArray[idx].advance (dt);
11+ }
12+ }
13+
14+ int main (int argc, char ** argv)
15+ {
16+ int n = 1000000 ;
17+ if (argc > 1 ) { n = atoi (argv[1 ]);} // Number of particles
18+ if (argc > 2 ) { srand (atoi (argv[2 ])); } // Random seed
19+
20+ particle * pArray = new particle[n];
21+ particle * devPArray = NULL ;
22+ cudaMalloc (&devPArray, n*sizeof (particle));
23+ cudaMemcpy (devPArray, pArray, n*sizeof (particle), cudaMemcpyHostToDevice);
24+ for (int i=0 ; i<100 ; i++)
25+ {
26+ float dt = (float )rand ()/(float ) RAND_MAX ; // Random distance each step
27+ advanceParticles<<< 1 + n/256 , 256 >>>(dt, devPArray, n);
28+ cudaDeviceSynchronize ();
29+ }
30+ cudaMemcpy (pArray, devPArray, n*sizeof (particle), cudaMemcpyDeviceToHost);
31+ v3 totalDistance (0 ,0 ,0 );
32+ v3 temp;
33+ for (int i=0 ; i<n; i++)
34+ {
35+ temp = pArray[i].getTotalDistance ();
36+ totalDistance.x += temp.x ;
37+ totalDistance.y += temp.y ;
38+ totalDistance.z += temp.z ;
39+ }
40+ float avgX = totalDistance.x /(float )n;
41+ float avgY = totalDistance.y /(float )n;
42+ float avgZ = totalDistance.z /(float )n;
43+ float avgNorm = sqrt (avgX*avgX + avgY*avgY + avgZ*avgZ);
44+ printf ( " Moved %d particles 100 steps. Average distance traveled is |(%f, %f, %f)| = %f\n " ,
45+ n, avgX, avgY, avgZ, avgNorm);
46+ return 0 ;
47+ }
0 commit comments