MPI并行计算学习笔记2——圆周率pi的并行求解
程序员文章站
2022-06-22 16:20:35
...
调式环境:VS2017 + MPI
圆周率PI的数值计算公式如下:
#include<iostream>
#include"mpi.h"
#include<ctime>
#include<cmath>
using namespace std;
const int N = 1000000;
double start,finish;//计算的起止时间
int main(int argc, char* argv[])
{
MPI_Init(&argc, &argv);//MPI库的初始化
int numprocs, myid;//定义进程总数及进程标识
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);//获得进程数
MPI_Comm_rank(MPI_COMM_WORLD, &myid);//获得当前进程标识号0,1,2,3,....,numprocs - 1
start = MPI_Wtime();//获得时间
double partSum = 0.0;//定义部分和
double pi = 0.0;//定义pi的值
for (int i = myid; i < N; i += numprocs)
{
partSum += sqrt(1 - (double(i) / N)*(double(i) / N)) / N;
//partSum += sqrt(1.0 - (double)(i * i) / (N * N))/N; int型乘法会有溢出问题
}
MPI_Reduce(&partSum, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
//规约操作,将各进程的partSum发送到0号进程并求和
cout << "我的标识是" << myid << ",求得的partSum值为:" << partSum << endl;
if (myid == 0)
{
pi *= 4.0;
finish = MPI_Wtime();
cout << "求得近似的pi值为:" << pi << endl;
cout<<"调用"<<numprocs<<"个进程的计算时间为:"<< finish - start<< endl;
}
MPI_Finalize();
//system("pause");
return 0;
}
分别调用1,2,3个进程,所得结果: