fork download
  1. #include <iostream>
  2. #include <cmath>
  3. #include <mpi.h>
  4. #include <fstream>
  5. #include <vector>
  6. #include <cstdlib> // for system function
  7.  
  8. using namespace std;
  9.  
  10. void writeDataToFile(const string& filename, int x, long double y) {
  11. ofstream file(filename, ios::app);
  12. if (file.is_open()) {
  13. printf("size and time: %f",y);
  14. file << x << " " << y<<" \n" << endl;
  15. file.close();
  16. }
  17. else {
  18. cerr << "Unable to open file for writing." <<endl;
  19. }
  20. }
  21.  
  22. double f(double x) {
  23. // Функция, которую мы интегрируем
  24. return cos(2*x+3)*sin(3*x) + 3;
  25. }
  26.  
  27. double simpson(double a, double b, int n, double h) {
  28. double sum = f(a) + f(b);
  29.  
  30. for (int i = 1; i < n; i += 2) {
  31. double x = a + i * h;
  32. sum += 4 * f(x);
  33. }
  34.  
  35. for (int i = 2; i < n - 1; i += 2) {
  36. double x = a + i * h;
  37. sum += 2 * f(x);
  38. }
  39.  
  40. return sum * h / 3.0;
  41. }
  42.  
  43.  
  44. int main(int argc, char** argv) {
  45.  
  46. const double a = 0.0;
  47. const double b = 1;
  48. const int n = 240000;
  49.  
  50. int rank, size=4;
  51. long double min_start = 4800000, max_end = 0, start, end, local_result, total_result;
  52.  
  53. MPI_Init(&argc, &argv);
  54. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  55. MPI_Comm_size(MPI_COMM_WORLD, &size);
  56. MPI_Barrier(MPI_COMM_WORLD);
  57.  
  58. start = MPI_Wtime();
  59.  
  60. cout << "Process " << rank << " of " << size << " is running." << endl;
  61.  
  62.  
  63. // Вычисляем локальный результат для каждого процесса
  64. int local_n = n / size;
  65. double local_a = a + rank * (b - a) / size;
  66. double local_b = local_a + (b - a) / size;
  67. double h = (b - a) / n;
  68.  
  69. local_result = simpson(local_a, local_b, local_n, h);
  70.  
  71.  
  72. MPI_Reduce(&local_result, &total_result, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  73. MPI_Barrier(MPI_COMM_WORLD);
  74. end = MPI_Wtime();
  75.  
  76.  
  77. if (rank == 0) {
  78. cout << "Total result: " << total_result << endl;
  79. }
  80.  
  81. int numproc;
  82.  
  83. numproc = size;
  84.  
  85.  
  86.  
  87. // Find max time
  88. if (min_start > start) {
  89. min_start = start;
  90. }
  91.  
  92. if (max_end < end) {
  93. max_end = end;
  94. }
  95.  
  96. if (rank == 0) {
  97. printf("Time taken to process: %f", (max_end - min_start));
  98. }
  99. if (rank == 0) {
  100. writeDataToFile("data.txt", numproc, (max_end - min_start));
  101. }
  102. MPI_Finalize();
  103.  
  104.  
  105.  
  106.  
  107. return 0;
  108. }
  109.  
  110.  
Success #stdin #stdout #stderr 0.27s 40768KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "using namespace"
Execution halted