From 1ebae14cf2a91dcf5ccd01d37cd5da7554a49d3d Mon Sep 17 00:00:00 2001 From: NFELIV <57617133+NFELIV@users.noreply.github.com> Date: Wed, 11 Mar 2020 19:34:47 +0300 Subject: [PATCH] =?UTF-8?q?13.=20=D0=9C=D0=B0=D0=BA=D1=81=D0=B8=D0=BC?= =?UTF-8?q?=D0=B0=D0=BB=D1=8C=D0=BD=D0=BE=D0=B5=20=D0=B7=D0=BD=D0=B0=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=8D=D0=BB=D0=B5=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D1=82=D0=BE=D0=B2=20=D0=BC=D0=B0=D1=82=D1=80=D0=B8=D1=86=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.cpp | 100 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 main.cpp diff --git a/main.cpp b/main.cpp new file mode 100644 index 0000000..4a9a309 --- /dev/null +++ b/main.cpp @@ -0,0 +1,100 @@ +#include "mpi.h" +#include +#include "locale" + + +int MaxSearch(const int* vector, const int n) //Поиск максимального +{ + int max; + if (n == 0) + { + return INT_MAX; + } + max = vector[0]; + for (int i = 0; i < n; i++) + { + if (max < vector[i]) + { + max = vector[i]; + } + } + return max; +} + +void OutputMatrix(const int* matrix, const int n, const int m) +{ + for (int i = 0; i < n; i++) + { + for (int j = 0; j < m; j++) + { + printf("%d ", matrix[i * m + j]); + } + printf("\n"); + } +} + +int main(int argc, char* argv[]) +{ + setlocale(LC_ALL, "Russian"); + if (argc != 3) + { + printf("Usage: %s, n, m \n", argv[0]); + printf("n - rows\n"); + printf("m - columns\n"); + return 1; + } + int* matrix = 0; + int n, m; + int max; + int proc_num, proc_rank; + int *send_counts, *displs, *recieve_buffer; + int chunk_size, rem; + double start, end; + MPI_Init(&argc, &argv); + MPI_Comm_size(MPI_COMM_WORLD, &proc_num); + MPI_Comm_rank(MPI_COMM_WORLD, &proc_rank); + n = atoi(argv[1]); + m = atoi(argv[2]); + if (proc_rank == 0) //Генерация + { + matrix = new int[n * m]; + srand(5); + for (int i = 0; i < n * m; i++) + { + matrix[i] = rand(); + } + if ((n < 10) && (m < 10)) + { + OutputMatrix(matrix, n, m); + } + } + start = MPI_Wtime(); + send_counts = new int[proc_num]; + displs = new int[proc_num]; + chunk_size = n * m / proc_num; + rem = n * m % proc_num; + send_counts[0] = chunk_size + rem; + displs[0] = chunk_size + rem; + for (int i = 0; i < proc_num; i++) + { + send_counts[i] = chunk_size; + displs[i] = rem + i * chunk_size; + } + recieve_buffer = new int[send_counts[proc_rank]]; + MPI_Scatterv(matrix, send_counts, displs, MPI_INT, recieve_buffer, send_counts[proc_rank], MPI_INT, 0, MPI_COMM_WORLD); + max = MaxSearch(recieve_buffer, send_counts[proc_rank]); + int GlobMax = 0; + MPI_Reduce(&max, &GlobMax, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD); + if (proc_rank == 0) + { + end = MPI_Wtime(); + printf("max= %d\n", GlobMax); + printf("Time spent: %lf\n", end - start); + delete matrix; + } + MPI_Finalize(); + delete[] send_counts; + delete[] displs; + delete[] recieve_buffer; + return 0; +}