Facebook
From sdasd, 3 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 85
  1. #include <iostream>
  2. #include <cmath>
  3. #include <ctime>
  4. #include <iomanip>
  5. #include <mpi.h>
  6.  
  7. using namespace std;
  8.  
  9. int prime_number(int n, int id, int numtask);
  10.  
  11.  
  12. int main(int argc, char **argv)
  13. {
  14.        
  15.             int n_factor=2; //krok
  16.         int n_lo=1;     //poczatek przedzialu
  17.         int n_hi=100;//koniec przedzialu
  18.        
  19.        
  20.     int nodeId,totalNode,len;
  21.     char hostname[MPI_MAX_PROCESSOR_NAME];
  22.     MPI_Status status;
  23.  
  24.     MPI_Init(&argc, &argv);
  25.     MPI_Comm_size(MPI_COMM_WORLD, &totalNode);
  26.     MPI_Comm_rank(MPI_COMM_WORLD, &nodeId);
  27.     MPI_Get_processor_name(hostname, &len);
  28.  
  29.  
  30.  
  31.     if(nodeId == 0 ) {
  32.         cout << "NODEID 0:  (ID: "<< nodeId <<") NODY: " << totalNode << endl;
  33.         cout << "       N_max           Ilosc liczb pierwszych          Czas " << endl;
  34.         cout << "n";
  35.     }
  36.  
  37.  
  38.         int n,p;
  39.         int primes,primes_part;
  40.         double startwtime,endwtime;
  41.  
  42.         n = n_lo;
  43.  
  44.         while (n <= n_hi)
  45.         {
  46.  
  47.         if ( nodeId == 0 )
  48.         {
  49.                 //ROZPOCZYNAM POMIAR CZASU
  50.           startwtime = MPI_Wtime();
  51.         }
  52. //ROZSYLANIE
  53.         MPI_Bcast( &n, 1, MPI_INT, 0, MPI_COMM_WORLD );
  54.  
  55.                 primes_part = prime_number( n, nodeId, totalNode );
  56.  
  57.                 MPI_Reduce( &primes_part, &primes, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD );
  58.  
  59.         if ( nodeId == 0 )
  60.         {
  61.             endwtime = MPI_Wtime();
  62.             cout << " " << setw(3) << n << " " << setw(18) << primes << " " << setw(18) <<  (endwtime-startwtime) << endl;
  63.         }
  64.  
  65.                 n = n*n_factor;
  66.         }
  67.  
  68.          MPI_Finalize();
  69.  
  70.  
  71.  
  72.         return 0;
  73. }
  74.  
  75.  
  76.  
  77. int prime_number(int n, int id, int numtask)
  78. {
  79.         int prime;
  80.         int total= 0;
  81.  
  82.         for (int i=2+id ; i<=n ; i=i+numtask)
  83.         {
  84.                 prime = 1;
  85.                 for (int j = 2; j < i; j++)
  86.                 {
  87.                         if ((i%j) == 0)
  88.                         {
  89.                                 prime = 0;
  90.                                 break;
  91.                         }
  92.                 }
  93.                 total = total + prime;
  94.         }
  95.         return total;
  96. }