|
| 1 | +#include "../../../nazyrov_a_a_vector_avg/mpi/include/ops_mpi.hpp" |
| 2 | + |
| 3 | +#include <mpi.h> |
| 4 | + |
| 5 | +#include <numeric> |
| 6 | + |
| 7 | +namespace nazyrov_a_a_vector_avg { |
| 8 | + |
| 9 | +VectorAvgMPI::VectorAvgMPI(const InType &in) : BaseTask() { |
| 10 | + GetInput() = in; |
| 11 | + MPI_Comm_rank(MPI_COMM_WORLD, &world_rank_); |
| 12 | + MPI_Comm_size(MPI_COMM_WORLD, &world_size_); |
| 13 | +} |
| 14 | + |
| 15 | +bool VectorAvgMPI::ValidationImpl() { |
| 16 | + return true; |
| 17 | +} |
| 18 | + |
| 19 | +bool VectorAvgMPI::PreProcessingImpl() { |
| 20 | + return true; |
| 21 | +} |
| 22 | + |
| 23 | +bool VectorAvgMPI::RunImpl() { |
| 24 | + const auto &input = GetInput(); |
| 25 | + int n = static_cast<int>(input.size()); |
| 26 | + int local_n = n / world_size_; |
| 27 | + int start = world_rank_ * local_n; |
| 28 | + int end = (world_rank_ == world_size_ - 1) ? n : start + local_n; |
| 29 | + |
| 30 | + double local_sum = std::accumulate(input.begin() + start, input.begin() + end, 0.0); |
| 31 | + int local_count = end - start; |
| 32 | + |
| 33 | + double global_sum = 0.0; |
| 34 | + int global_count = 0; |
| 35 | + |
| 36 | + MPI_Reduce(&local_sum, &global_sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); |
| 37 | + MPI_Reduce(&local_count, &global_count, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); |
| 38 | + |
| 39 | + if (world_rank_ == 0) { |
| 40 | + GetOutput() = global_sum / static_cast<double>(global_count); |
| 41 | + } |
| 42 | + |
| 43 | + return true; |
| 44 | +} |
| 45 | + |
| 46 | +bool VectorAvgMPI::PostProcessingImpl() { |
| 47 | + return true; |
| 48 | +} |
| 49 | + |
| 50 | +} // namespace nazyrov_a_a_vector_avg |
0 commit comments