MPI学习笔记(1)

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

1)配置mpi环境

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

  1. #include <stdio.h> 
  2. #include <math.h> 
  3. #include "mpi.h" 
  4. int main(int argc,char *argv[]) 
  5.     int i,j,k,n,myid,numprocs,namelen; 
  6.     char processor_name[MPI_MAX_PROCESSOR_NAME]; 
  7.     double startwtime=0.0,endwtime; 
  8.     float mysum, sum; 
  9.     MPI_Init(&argc,&argv); 
  10.      MPI_Comm_rank(MPI_COMM_WORLD,&myid); 
  11.     MPI_Comm_size(MPI_COMM_WORLD,&numprocs); 
  12.     MPI_Get_processor_name(processor_name,&namelen); 
  13.     n = 1; 
  14.     for(j = 1; j <= 1000; ++j) { 
  15.         mysum = 0; 
  16.         for(k = myid + 1; k <= 16; k += numprocs) { 
  17.             mysum += k; 
  18.         } 
  19.         MPI_Reduce(&mysum,&sum,1,MPI_FLOAT,MPI_SUM,0,MPI_COMM_WORLD); 
  20.     } 
  21.     for(i = 1; i <= 14; ++i) { 
  22.          n = n << 2; 
  23.          startwtime=MPI_Wtime(); 
  24.          for(j = 1; j <= 100; ++j) { 
  25.             mysum = 0; 
  26.             for(k = myid + 1; k <= n; k += numprocs) { 
  27.                 mysum += k; 
  28.             } 
  29.             MPI_Reduce(&mysum,&sum,1,MPI_FLOAT,MPI_SUM,0,MPI_COMM_WORLD); 
  30.          } 
  31.          if (myid == 0) { 
  32.              fprintf(stderr,"4^%d: total 100 times cost:%lf s and result is %f/n", i 
  33.                 , (MPI_Wtime() - startwtime), sum); 
  34.           } 
  35.     } 
  36.     MPI_Finalize(); 
  37.     return 0; 
#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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值