Parallel computing program trapezoid integration method

Analysis process of parallel computing

1. Decompose the problem into multiple subproblems
2. Assign solving tasks to each process
3. Summarize and calculate the results
Parallel program design is similar to the analysis process of divide and conquer method. If you want to understand the design idea of divide and conquer method
Divide and conquer algorithm design and analysis
The advantage of parallel program compared with serial program is that it makes good use of cpu resources, so that multiple processors can solve a problem at the same time.
Here we calculate the area of f(x) = x^2 + 2*x + 1; function on [0,3]
The installation and use of MPI in the code can be found on the Internet.

MPI is different from common C programs in compiling and executing commands

mpicc -o test test.c compile command
Mpirun - NP 4. / test execute the command (execute the program in parallel with four processes)

#include <stdio.h>
#include "mpi.h"
#include <unistd.h>

//Quadratic function
double Fun(double x)
{
    return x*x+2*x+1;    
}

//Area solution between single processes
//n is the number of times of accumulation, and m is the span between adjacent elements
double Area(int n,double m,double start)
{
    double title_d = 0;
    int i = 0;
    for(; i < n; i++)
    {
        double tmp = Fun(start);
        double area = m*tmp;
        title_d += area;
        start += m;
    }
    //printf("process number:% d = >% f \ n", getpid(), title_d);
    return title_d;
}

int main()
{
	//rank indicates the current process number
	//size indicates the total number of processes
    int rank,size;
	
	//Solved interval [0,3]
    double a = 0.0,b = 3.0;
    //Divide the interval into 1024 parts
    int num = 1024; 
    //Initialization
    MPI_Init(NULL,NULL);
    //Getting the current process number from 0 is not pid
    MPI_Comm_rank(MPI_COMM_WORLD,&rank);
    //Get the number of processes
    MPI_Comm_size(MPI_COMM_WORLD,&size);
    
    //Divide into 1024 parts, and calculate the width of each part
    double m = (b-a)/num;
    //Count the number of times each process needs to count
    int n = num/size;

	//
    double start = a + rank*m*n;
    double title_int = Area(n,m,start);
    if(rank != 0)
    {
    	//MPI_Send() function for interprocess communication,
    	//Send the calculation result to process 0 here
    	//Process 0 is used to count all results
        MPI_Send(&title_int,1,MPI_DOUBLE,0,0,MPI_COMM_WORLD);
    }
    else
    {
        double title = 0.0;
        int i = 0;
        for(i = 1; i < size; i++)
        {
        //Process 0 counts all calculations
            title += title_int;
   MPI_Recv(&title_int,1,MPI_DOUBLE,i,0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
        }
        title += title_int;
        printf("The measure of area:%f\n",title);
    }
    
    //End releasing resources
    MPI_Finalize();
    return 0;    
}

Posted on Mon, 02 Dec 2019 02:35:03 -0800 by Riparian