Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Par_prog_lab1.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <iostream>
- #include <cmath>
- #include <mpi.h>
- #include <ctime>
- using namespace std;
- double f(double x);
- double rectangle_method(double a, double b, int n) {
- double h = (b - a) / n;
- double sum = 0.0;
- for (int i = 0; i < n; ++i) {
- double x = a + h * (double)i;
- sum += f(0.5 * (x + x + h));
- }
- return h * sum;
- }
- double f(double x) {
- return sin(x);
- }
- inline void solve(double a, double b, int n) {
- long long l = clock();
- double ans = rectangle_method(a, b, n);
- cout << "Sequential I(x) = " << ans << endl;
- cout << "Sequential time: " << (double)(clock() - l) / CLOCKS_PER_SEC << endl << endl;
- }
- int main(int argc, char** argv)
- {
- cout.precision(5);
- cout.setf(ios::fixed);
- double a, b , n;
- a = 0;
- b = 10000;
- n = 1e9;
- MPI_Status status;
- MPI_Init(&argc, &argv);
- int cur_proc, total;
- MPI_Comm_size(MPI_COMM_WORLD, &total);
- MPI_Comm_rank(MPI_COMM_WORLD, &cur_proc);
- if (cur_proc == 0) {
- solve(a, b, n);
- }
- double cur_a, cur_b;
- int cur_n;
- double sum = 0, part = 0;
- long long start = clock();
- if (cur_proc == 0) {
- double step = (b - a) / total;
- cur_a = a;
- cur_b = a + step;
- cur_n = (int)n / total;
- for (int i = 1; i < total; ++i) {
- MPI_Send(&cur_a, 1, MPI_DOUBLE, i, 100, MPI_COMM_WORLD);
- MPI_Send(&cur_b, 1, MPI_DOUBLE, i, 101, MPI_COMM_WORLD);
- MPI_Send(&cur_n, 1, MPI_INT, i, 102, MPI_COMM_WORLD);
- cur_a = cur_b;
- cur_b += step;
- }
- }
- else {
- MPI_Recv(&cur_a, 1, MPI_DOUBLE, 0, 100, MPI_COMM_WORLD, &status);
- MPI_Recv(&cur_b, 1, MPI_DOUBLE, 0, 101, MPI_COMM_WORLD, &status);
- MPI_Recv(&cur_n, 1, MPI_INT, 0, 102, MPI_COMM_WORLD, &status);
- }
- //cout << "Hello from " << cur_proc << " process" << endl;
- part = rectangle_method(cur_a, cur_b, cur_n);
- if (cur_proc == 0) {
- sum = part;
- for (int i = 1; i < total; ++i) {
- MPI_Recv(&part, 1, MPI_DOUBLE, i, 103, MPI_COMM_WORLD, &status);
- sum += part;
- }
- }
- else {
- MPI_Send(&part, 1, MPI_DOUBLE, 0, 103, MPI_COMM_WORLD);
- }
- if (cur_proc == 0) {
- long long end = clock();
- cout << "Paralell I(x) = " << sum << endl;
- cout << "Paralell time: " << (double)(end - start) / CLOCKS_PER_SEC << endl;
- system("pause");
- }
- MPI_Finalize();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement