简体   繁体   English

C程序转MPI并行程序

[英]C program to MPI parallel program

Hello i don't know if this is the right place to ask that.你好,我不知道这是否是问这个问题的正确地方。 I have this MPI parallel Code that calculates PI and i need help understanding it for an oral exam.我有这个计算 PI 的 MPI 并行代码,我需要帮助理解它以进行口试。

#include <mpi.h>
#include <math.h>

int main(argc,argv)

int argc;

char *argv[];

{

    int done = 0, n, myid, numprocs, i;
    double PI25DT = 3.141592653589793238462643;
    double mypi, pi, h, sum, x;

    MPI_Init(&argc,&argv);
    MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD,&myid);
    while (!done)
    {
    if (myid == 0) {
        printf("Enter the number of intervals: (0 quits) ");
        scanf("%d",&n);
    }
    MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);

    if (n == 0) break;

    h   = 1.0 / (double) n;
    sum = 0.0;
    for (i = myid + 1; i <= n; i += numprocs) {
        x = h * ((double)i - 0.5);
        sum += 4.0 / (1.0 + x*x);
    }
    mypi = h * sum;

    MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0,
           MPI_COMM_WORLD);

    if (myid == 0)
        printf("pi is approximately %.16f, Error is %.16f\n",
           pi, fabs(pi - PI25DT));
    }
    MPI_Finalize();
    return 0;
}

Read this: MPI阅读: MPI

Starting from top: MPI_Init(&argc,&argv);从顶部开始: MPI_Init(&argc,&argv); is used to pass the command line arguments to all processes.用于将命令行参数传递给所有进程。

MPI_Comm_size(MPI_COMM_WORLD,&numprocs); MPI_Comm_rank(MPI_COMM_WORLD,&myid); returns the total number of MPI processes in the specified communicator (like MPI_COMM_WORLD) and their rank from pool.返回指定通信器(如 MPI_COMM_WORLD)中的 MPI 进程总数及其从池中的排名。

MPI_Bcast Broadcasts (sends) a message from the process with rank "root" to all other processes in the group.(Here sending the number of iteration to every other process) MPI_Bcast从等级为“root”的进程向组中的所有其他进程广播(发送)一条消息。(这里将迭代次数发送到每个其他进程)

Between should be proper Monte Carlo pi estimation code.之间应该是适当的蒙特卡罗 pi 估计代码。

And then the MPI_Reduce to Collect the areas calculated.然后MPI_Reduce来收集计算的区域。

After that root prints the final pi value with error correction PI25DT .之后 root 打印带有纠错PI25DT的最终 pi 值。

Lastly MPI_Finalize() Terminates the MPI execution environment.最后MPI_Finalize()终止 MPI 执行环境。 This function should be the last MPI routine called in every MPI program - no other MPI routines may be called after it.这个函数应该是每个 MPI 程序中调用的最后一个 MPI 例程——在它之后不能调用其他 MPI 例程。

Pseudo for Monte Carlo Pi: Monte Carlo Pi 的伪代码:

 for(i = 0; i < n; ++i) {

 x = (double)rand() / RAND_MAX;

 y = (double)rand() / RAND_MAX;

 z = x * x + y * y;

 if( z <= 1 ) count++;
 }

 pi = (double) count / n * 4;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM