MPI学习笔记(1)

今天开始学习写MPI,基本过程:

1)配置mpi环境

2)拿一小段MPI代码试验,来自:http://blog.csdn.net/zhuliting/article/details/5868425

#include <stdio.h>
#include <math.h>
#include "mpi.h"
int main(int argc,char *argv[])
{
 	int i,j,k,n,myid,numprocs,namelen;
 	char processor_name[MPI_MAX_PROCESSOR_NAME];
 	double startwtime=0.0,endwtime;
 	float mysum, sum;
 	MPI_Init(&argc,&argv);
	 MPI_Comm_rank(MPI_COMM_WORLD,&myid);
 	MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
 	MPI_Get_processor_name(processor_name,&namelen);
	n = 1;
    for(j = 1; j <= 1000; ++j) {
     	mysum = 0;
        for(k = myid + 1; k <= 16; k += numprocs) {
  			mysum += k;
     	}
        MPI_Reduce(&mysum,&sum,1,MPI_FLOAT,MPI_SUM,0,MPI_COMM_WORLD);
 	}
 	for(i = 1; i <= 14; ++i) {
 		 n = n << 2;
         startwtime=MPI_Wtime();
         for(j = 1; j <= 100; ++j) {
   			mysum = 0;
  			for(k = myid + 1; k <= n; k += numprocs) {
    			mysum += k;
   			}
            MPI_Reduce(&mysum,&sum,1,MPI_FLOAT,MPI_SUM,0,MPI_COMM_WORLD);
 		 }
		 if (myid == 0) {
			 fprintf(stderr,"4^%d: total 100 times cost:%lf s and result is %f/n", i
				, (MPI_Wtime() - startwtime), sum);
          }
 	}
 	MPI_Finalize();
 	return 0;
}


3)编译运行

编译:mpicxx sum.cpp -o sum

执行:mpirun -np 4 ./sum


©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页