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(6*x)*sin(5*x) + 4;
  25. }
  26.  
  27.  
  28.  
  29. double trapezoidal(double a, double b, int n, double h) {
  30. double sum = 0.5 * (f(a) + f(b));
  31.  
  32. for (int i = 1; i < n; ++i) {
  33. double x = a + i * h;
  34. sum += f(x);
  35. }
  36.  
  37. return sum * h;
  38. }
  39.  
  40. int main(int argc, char** argv) {
  41.  
  42. const double a = 0.0;
  43. const double b = 1;
  44. const int n = 120000;
  45.  
  46. int rank, size;
  47. long double min_start = 120000, max_end = 0, start, end, local_result, total_result;
  48.  
  49. MPI_Init(&argc, &argv);
  50. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  51. MPI_Comm_size(MPI_COMM_WORLD, &size);
  52. MPI_Barrier(MPI_COMM_WORLD);
  53.  
  54. start = MPI_Wtime();
  55.  
  56. cout << "Process " << rank << " of " << size << " is running." << endl;
  57.  
  58.  
  59. // Вычисляем локальный результат для каждого процесса
  60. int local_n = n / size;
  61. double local_a = a + rank * (b - a) / size;
  62. double local_b = local_a + (b - a) / size;
  63. double h = (b - a) / n;
  64. //local_result = rectangle_integration(local_a, local_b, local_n);
  65. //local_result = simpson(local_a, local_b, local_n, h);
  66. local_result = trapezoidal(local_a, local_b, local_n, h);
  67.  
  68. MPI_Reduce(&local_result, &total_result, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
  69. MPI_Barrier(MPI_COMM_WORLD);
  70. end = MPI_Wtime();
  71.  
  72.  
  73. if (rank == 0) {
  74. cout << "Total result: " << total_result << endl;
  75. }
  76.  
  77. int numproc;
  78.  
  79. numproc = size;
  80.  
  81.  
  82.  
  83. // Find max time
  84. if (min_start > start) {
  85. min_start = start;
  86. }
  87.  
  88. if (max_end < end) {
  89. max_end = end;
  90. }
  91.  
  92. if (rank == 0) {
  93. printf("Time taken to process: %f", (max_end - min_start));
  94. }
  95. if (rank == 0) {
  96. writeDataToFile("data.txt", numproc, (max_end - min_start));
  97. }
  98. MPI_Finalize();
  99.  
  100.  
  101.  
  102.  
  103. return 0;
  104. }
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