pborawski

współbieżne pi

Jan 21st, 2013
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.20 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <mpi.h>
  5. #include <math.h>
  6.  
  7. #define PI 3.14159265358979311600
  8. #define LOOPS 10000
  9.  
  10. double losuj()
  11. {
  12.     return ( (double)rand() / (double)RAND_MAX );
  13. }
  14.  
  15.  
  16. int main(int argc, char *argv[])
  17. {
  18.    
  19.     double x,y;
  20.     double pi;
  21.    
  22.     int myid,numproc;
  23.    
  24.     long int kolo = 0.0;
  25.     long int nSum, i;
  26.     double czas1;
  27.     double czas2;
  28.    
  29.     srand(time(NULL));
  30.    
  31.     MPI_Init(&argc, &argv);
  32.     MPI_Comm_rank(MPI_COMM_WORLD, &myid);
  33.     MPI_Comm_size(MPI_COMM_WORLD, &numproc);
  34.    
  35.    
  36.    
  37.     czas1 = MPI_Wtime();
  38.    
  39.     for( i = 0; i < LOOPS/numproc; i++ )
  40.     {
  41.         x = ( (double)rand() / (double)RAND_MAX );
  42.         y = ( (double)rand() / (double)RAND_MAX );
  43.        
  44.         if( x * x + y * y < 1.0)
  45.             kolo++;
  46.        
  47.         MPI_Allreduce(&kolo, &nSum, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
  48.         MPI_Barrier(MPI_COMM_WORLD);
  49.            
  50.         pi = ( (double)nSum * 4.0 ) / ( (double)LOOPS );
  51.        
  52.        
  53.        
  54.     }
  55.    
  56.     czas2 = time(NULL);
  57.    
  58.     if(myid == 0)
  59.     {
  60.         printf("Czas potrzebny na obliczenie: %lf\n", czas2 - czas1);
  61.         printf("Dana liczba pi: %1.20f\n", PI);
  62.         printf("obliczona wartość pi: %1.20f dla %ld/%ld trafień do koła z wszystkich losowań\n", pi, nSum, LOOPS);
  63.     }
  64.    
  65.    
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment