欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MPI并行编程

程序员文章站 2022-07-12 21:34:20
...


1.MPI简介
(回顾并行编程的四种模式)
SIMD-单指令多数据处理器是“锁步”:每个处理器对不同数据同步执行单指令。
SPMD-单程序多数据处理器的异步运行一个程序的个人副本。
MIMD-多指令多数据处理器异步运行:每个处理器都有自己的数据和自己的指令。
MPMD-多程序多数据处理器异步运行:每个处理器都有自己的数据和自己的程序。
    (1)分布式内存和共享内存
           分布式内存指的是多处理器计算机系统中,每个处理器都有自己的私有内存。计算任务只能对本地数据进行操作,如果需要远程数据,计算任务必须与一个或多个远程处理器通信。与此相反,共享内存多处理机提供了可供所有处理器使用的单个内存空间。
            分布式内存:每个进程有自己的地址空间,所以对每个进程来说数据是本地的;数据共享通过显式消息传递实现(通过网络)。---如:MPI
对于分布式内存系统,发送方进程发出一个发送调用,而接收方进程发出一个相应的接收调用。
            ②共享内存:共享内存是由多个程序同时访问的内存,其目的是提供它们之间的通信或避免冗余副本。共享内存系统可以使用:
               UMA(统一内存访问 uniform memory access):所有处理器共享内存的一致
               NUMA(非统一内存访问non-uniform memory access):内存访问时间取决于内存位置相对于处理器
               COMA(cache-only memory architecture):每个节点的处理器的本地存储器用作缓存,而不是作为实际主存。
               共享内存中,所有线程可以访问的全局地址空间。数据共享通过/读写相同的内存位置的实现。
    (2)什么是MPI
 Message Passing Interface :消息传递接口
           MPI是由一组来自学术界和工业界的研究人员建立在各种并行计算体系结构设计的一个标准化的和便携式的消息传递系统。该标准定义了一个核心库例程的语法和语义,这些库例程对于广大用户用C,C++和Fortran编写可移植的消息传递程序很有用
            MPI为消息传递定义了一个标准的API接口。标准包括:一组核心函数的语法和语义;标准不包括:实施细节和运行时细节(代码存在于多少进程)。MPI提供了C/C++和Fortran绑定。
    (3)为什么使用MPI?
标准化Standardized:并行编程的事实标准。
可移植性Portability:几乎所有平台都可以使用MPI实现。
可伸缩性Scalability:在某种意义上,它不受可以访问相同内存空间的处理器数量的限制。
流行性广泛性Popularity:许多库是基于MPI,如PETSc,MPE,ScaLAPACK,PLAPACK等。
    (4) MPI的标准中包括什么?
           点对点通信;集群操作;进程组、通信上下文和进程拓扑;环境管理和调查;过程创建和管理;其他功能。
           编程结构:Initialization and Termination、Getting Communicator Information
  1. # include "mpi.h"
  2. int main (int argc, char *argv[]){
  3. MPI_Init (&argc, &argv);
  4. MPI_Comm_size (COMM, &p);
  5. MPI_Comm_rank (COMM, &id);
  6. Communicate & Compute;
  7. MPI_Finalize( );
  8. return 0;
  9. }
            Communicator:Encapsulate all of these ideas in order to provide the appropriate scope for all communication operations。
           可被看做一组有序的进程,每个进程有一个独有的rank,是运行背景。
MPI_COMM_WORLD,默认的communicator,包含所有进程,它是MPI定义的允许程序里所有进程运行期间互相通信的通信者,或者是点对点通信,又或者是集合通信。然而对于一些应用,可能需要在选定的一个子进程组里进行通信。
           通信者有两类:内部通信者(intra-communicator)和互联通信者(inter-communicator)。内部通信者处理通信者个体里的 进程间的通信,而互联通信者处理内部通信者之间的通信。A process can belong to multiple communicators.本质上来说,内部通信者是MPI_COMM_WORLD的进程的子集。我们主要专注于内部通信者。需要新的通信者的原因经常是因为要处理矩阵的行、列或子块等需求。这些通信者通常和一个虚拟拓扑关联--比笛卡尔拓扑常用--来辅助并行操作的实现。此外,通信者的使用,经常和虚拟拓扑一起,通常增强了程序的可读性和可维护性。
            1)点对点通信:点对点通信是MPI中最基本的通信形式,它允许程序通过一个特定的communicator将消息从一个进程发送到另一个进程。源进程发送消息到目的地的过程;通信发生在一个communicator中;目的地的过程是通过它在通信子的rank。
           注意:“Completion完成”意味着可以安全地访问消息传递中使用的内存位置。对于发送者:发送变量在完成后可以重复使用。对于接收者:接收到的变量现在可以使用。
MPI通信方式的不同在于,接收端的完成需要什么条件——通信模式可以阻塞或非阻塞。
阻塞:函数调用的返回意味着完成;
非阻塞:从调用返回而不等待任务完成。
           **阻塞通信模式:
           ①标准模式:由MPI来决定传出的消息是否会被缓冲。
           MPI可以缓冲区发送消息。在调用相应的的接收之前,发送调用可以完成。
           MPI不能缓冲区发送消息。直到匹配的接收被发送,数据已被移动到接收方时,发送调用才会完成。标准模式发送是non-local非本地的:发送操作的成功完成可能取决于相应接收的发生。
           ②缓冲模式无论是否已有对应的接收发送操作都可以启动。
           发送可以在匹配接收之前完成。
           它是本地的:完成并不取决于匹配接收的发生。如果冲空间不足,会出现错误。可用的缓冲区空间的数量是由用户控制。想要缓冲模式有效,由用户来分配的缓冲区可能是必须的
           ③同步模式:Send can start whether or not a matching receive was posted。
           发送只有当匹配的接收发布,且接收操作开始接收发送端同步发送的消息时才会完成。这种模式是非本地的。
           ④ready mode:只有当匹配接收已经发布时,才可以开始发送。发送不取决于匹配的接收的状态,而仅仅表明发送缓冲区可以重复使用。
         **非阻塞通信模式:重叠的通信和计算
           非阻塞发送(接收)的开始调用启动发送(接收)的操作,但不完成它。因此,在缓冲区可以安全地重新使用之前,发送/接收就将返回。完成通信需要单独的发送/接收完成调用,确认数据已经转移。非阻塞接收的使用也可避免系统缓存和内存到内存的复制。
           把非阻塞通信分为三个部分:
           初始化非阻塞传输->做一些不涉及传输中的数据的其他工作->等待非阻塞通信完成.
            函数的句法结构:例如 MPI_Isend 函数int MPI_Isend(const void* buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm, MPI_Request *request) 

            2)集群通信:一对多 多对一 多对多 
           集群通信的三中类型:数据移动 Data movement•集体计算Collective computation•同步Synchronization
            All collective communications are blocking
         集群通信与点对点通信的对比:
           a.更简洁的程序:一个集体的操作可以代替多个点对点的操作
           b.优化的集体通信通常比相应的点对点通信速度更快
            Data movement(看图)
            ①Broadcast copies data from the memory of one processor to that of other processors —— One to all operation;
            ②Gather copies data from each process to one process, where it is stored in rank order—— One to all operation;
            ③Scatter:Typically data is in an array on the root process and we want to send a different portion of the array to each worker process (often including the root);
            ④Gather-to-all:The block of data sent from the j-th process is received by every process and placed in the j-th block of the buffer recvbuf;
            ⑤All-to-all:The j-th block sent from process i is received by process j and is placed in the i-th block of recvbuf。
            Collective computation
            ①Reduce:MPI reduction collects data from each process, reduces them to a single value, and store it in the memory of one process;
            ②MPI allreduce collects data from each process, reduces them to a single value, and store it in the memory of EVERY process;
            ③Scan performs a prefix reduction on data distributed across the group. The operation returns, in the receive buffer of the process with rank i, the reduction of the values in the send buffers of processes with ranks 0,…,i(inclusive).

            (5)并行程序设计parallel programs
            ①分解。将要执行的计算和由该计算操作的数据分解成小任务。
            ②通信。协调任务执行所需的通信是确定了的,并定义了适当的通信结构和算法。
            ③聚集。在设计的前两个阶段中定义的任务和通信结构将根据性能要求和实现成本进行评估。如果有必要,将任务组合成更大的任务,以提高性能或降低开发成本。
            ④映射。每个任务被分配给处理器,试图满足最大化处理器利用率和最小化通信成本的竞争目标。映射可以指定静态或在运行时确定的负载均衡算法。




白话补充~~
MPI是分布式计算的基础接口架构,他有很多实现,比如intelMPI openMPI等等,而这些具体实现了这些接口里面的内容,比如一些通信协议。MPI有几个很重要的概念rank, group, communicator, type, pack, spawn, window, 理解了这些概念MPI就算入门了。
 
group是MPI一个很重要的概念,一台电脑可以属于多个group,group的正真强大体现在可以随时随地的组合任意group,然后利用gourp内,和group间的communicator,可以很容易实现复杂科学计算的中间过程,比如奇数rank一个group,偶数另一个group,或者拓扑结构的group,这样可以解决很多复杂问题,另外MPI还有一个默认的全局的group,他就是comm world,一般简单的应用有了这一个group已经足够了。
 
rank就是任意group内的一个计算单元,利用rank我们可以很轻松的实现client server的架构,比如rank=0是server其他就是client。
 
communicator就是各种通信,比如一对一,一对多,多对一,其中多往往代表着一个group, 在传输过程中tag还是很有用的可以用来区别不同的任务类型,一般都是先解析tag,然后再解析具体的数据内容, 这里要有一个信封和信内容的差别的概念,理解了这样的差别,可以很好的扩展程序。

type是MPI的自定义类型,由于通常编程的时候常用struct 数组 和离散的变量,这些东西不能直接进行通信, 然后MPI同样有一套这样的定义,我们可以转化成MPI的格式,这样就可以很*的通信了。
 
Pack,就是把离散的数据打包起来,方便传送,其实这个作用和type很类似,如果你不想很麻烦的定义type直接打包发送。
spawn是区分MPI一代和二代的一个重要的标志,有了spawn,就可以在运行过程中自动的改变process的数量,可能复杂的软件才有这样的需求。
 
window远程的控制同一个文件,只有在网络条件很好的时候用这个才有意义,否则会让软件效率变得很糟糕。


2.API总结

<点对点>
  1. MPI_Send(//标准模式
  2. void* data,//starting address of the data to be sent
  3. int count,
  4. MPI_Datatype datatype,
  5. int destination,
  6. int tag,
  7. MPI_Comm comm)
  1. MPI_Recv(
  2. void* data,//starting address of buffer to store message
  3. int count,
  4. MPI_Datatype datatype,
  5. int source,
  6. int tag,
  7. MPI_Comm comm,
  8. MPI_Status* status)
buffered mode: MPI_BSend 
Synchronous mode : MPI_Ssend
Ready mode : MPI_Rsend

<集合通信> ——都是blocking的
三种类型:数据移动、集合计算、同步
数据移动:
  1. int MPI_Bcast(//one to all 操作
  2. void* buffer,
  3. int count,
  4. MPI_Datatype datatype,
  5. int root,
  6. MPI_Comm comm)
  1. int MPI_Gather(//one to all 操作
  2. const void* sendbuf,
  3. int sendcount,
  4. MPI_Datatype sendtype,
  5. void* recvbuf,//address of receive buffer (significant only at root)
  6. int recvcount,
  7. MPI_Datatype recvtype,
  8. int root,//rank of receiving process
  9. MPI_Comm comm)
gather 例:
MPI并行编程
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. #include<string.h>
  5. #include<mpi.h>
  6. int main(int argc, char** argv)
  7. {
  8. MPI_Comm comm = MPI_COMM_WORLD;
  9. int size,rank,sbuf[3],*rbuf,i;
  10. MPI_Init(&argc, &argv);
  11. MPI_Comm_size(comm, &size);
  12. MPI_Comm_rank(comm, &rank);
  13. for(i=0;i<3;i++)
  14. sbuf[i]=rank*10+i;//每一个进程都有一个sbuf
  15. if(rank==0)
  16. rbuf=(int*)malloc(sizeof(int)*3*size);//只有root里才分配内存
  17. MPI_Gather(sbuf,3,MPI_INT,rbuf,3,MPI_INT,0,MPI_COMM_WORLD);
  18. if(rank==0)
  19. {
  20. printf("Process 0 receives:");
  21. for(i=0;i<size*3;i++)
  22. printf("%d",rbuf[i]);
  23. putchar('\n');
  24. }
  25. MPI_Finalize();
  26. return 0;
  27. }

  1. int MPI_Scatter (
  2. void * sendbuf , // pointer to send buffer
  3. int sendcount , // items to send per process
  4. MPI_Datatype sendtype , // type of send buffer data
  5. void * recvbuf , // pointer to receive buffer
  6. int recvcount , // number of items to receive
  7. MPI_Datatype recvtype , // type of receive buffer data
  8. int root , // rank of sending process
  9. MPI_Comm comm )
scatter例:
MPI并行编程
 
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. #include<string.h>
  5. #include<mpi.h>
  6. int main(int argc, char** argv)
  7. {
  8. MPI_Comm comm = MPI_COMM_WORLD;
  9. int size,rank,*sbuf,rbuf[3],i;
  10. MPI_Init(&argc, &argv);
  11. MPI_Comm_size(comm, &size);
  12. MPI_Comm_rank(comm, &rank);
  13. if(rank==0)
  14. {
  15. sbuf=(int*)malloc(sizeof(int)*3*size);//只有root里才分配内存
  16. for(i=0;i<size*3;i++) sbuf[i]=i+1;
  17. }
  18. MPI_Scatter(sbuf,3,MPI_INT,rbuf,3,MPI_INT,0,MPI_COMM_WORLD);//每个进程都有一个rbuf
  19. printf("Process %d receives:",rank);
  20. for(i=0;i<3;i++)
  21. printf("%d ",rbuf[i]);
  22. putchar('\n');
  23. MPI_Finalize();
  24. return 0;
  25. }

  1. int MPI_Allgather (
  2. void * sendbuf , // pointer to send buffer
  3. int sendcount , // number of items to send
  4. MPI_Datatype sendtype , // type of send buffer data
  5. void * recvbuf , // pointer to receive buffer
  6. int recvcount , // items to receive per process
  7. MPI_Datatype recvtype , // type of receive buffer data
  8. MPI_Comm comm )
allgather例:
MPI并行编程
 
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. #include<string.h>
  5. #include<mpi.h>
  6. int main(int argc, char** argv)
  7. {
  8. MPI_Comm comm = MPI_COMM_WORLD;
  9. int size,rank,sbuf[3],*rbuf,i;
  10. MPI_Init(&argc, &argv);
  11. MPI_Comm_size(comm, &size);
  12. MPI_Comm_rank(comm, &rank);
  13. for(i=0;i<3;i++)
  14. sbuf[i]=rank*10+i;
  15. rbuf=(int*)malloc(sizeof(int)*3*size);
  16. MPI_Allgather(sbuf,3,MPI_INT,rbuf,3,MPI_INT,MPI_COMM_WORLD);
  17. printf("Process %d receives:",rank);
  18. for(i=0;i<size*3;i++)
  19. printf("%d",rbuf[i]);
  20. putchar('\n');
  21. free(rbuf);
  22. MPI_Finalize();
  23. return 0;
  24. }

  1. int MPI_Alltoall(
  2. const void *sendbuf,
  3. int sendcount,
  4. MPI_Datatype sendtype,
  5. void *recvbuf,
  6. int recvcount,
  7. MPI_Datatype recvtype,
  8. MPI_Comm comm)
all-to-all:
MPI并行编程
 
  1. int main(int argc, char** argv){
  2. int rank, size, *sbuf, *rbuf, i;
  3. MPI_Init(&argc, &argv);
  4. MPI_Comm_size(MPI_COMM_WORLD, &size);
  5. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  6. sbuf = (int*)malloc(size * 3 * sizeof(int));
  7. rbuf = (int*)malloc(size * 3 * sizeof(int));
  8. for (i = 0; i < size * 3; i++)
  9. sbuf[i] = rank * 10 + i;
  10. printf("Before exchange, process %d has ", rank);
  11. for (i = 0; i < size * 3; i++)
  12. printf("%d ", sbuf[i]);
  13. putchar('\n');
  14. MPI_Alltoall(sbuf, 3, MPI_INT, rbuf, 3, MPI_INT, MPI_COM
  15. M_WORLD);
  16. printf("After exchange, process %d has ", rank);
  17. for (i = 0; i < size * 3; i++)
  18. printf("%d ", rbuf[i]);
  19. putchar('\n');
  20. MPI_Finalize();
  21. free(sbuf);
  22. free(rbuf);
  23. return 0;
  24. }
集合计算:
  1. MPI_Reduce(
  2. void* send_data,
  3. void* recv_data,
  4. int count,
  5. MPI_Datatype datatype,
  6. MPI_Op op,//reduce操作类型
  7. int root,
  8. MPI_Comm communicator)
reduce例1:
MPI并行编程
 
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. #include<string.h>
  5. #include<mpi.h>
  6. int main(int argc, char** argv)
  7. {
  8. MPI_Comm comm = MPI_COMM_WORLD;
  9. int size,rank,sbuf[3],rbuf[3],i;
  10. MPI_Init(&argc, &argv);
  11. MPI_Comm_size(comm, &size);
  12. MPI_Comm_rank(comm, &rank);
  13. for(i=0;i<3;i++)
  14. sbuf[i]=rank*10+i;
  15. printf("Process %d has:",rank);
  16. for(i=0;i<3;i++) printf("%d",sbuf[i]);
  17. putchar('\n');
  18. MPI_Reduce(sbuf,rbuf,3,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD);
  19. if(rank==0)
  20. {
  21. printf("Total=");
  22. for(i=0;i<3;i++)
  23. printf("%d",rbuf[i]);
  24. putchar('\n');
  25. }
  26. MPI_Finalize();
  27. return 0;
  28. }
reduce例2(max location):
MPI并行编程
 
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. #include<string.h>
  5. #include<mpi.h>
  6. typedef struct
  7. {
  8. int val;
  9. int rank;
  10. }DATATYPE;
  11. int main(int argc, char** argv)
  12. {
  13. MPI_Comm comm = MPI_COMM_WORLD;
  14. int size,rank,i;
  15. DATATYPE sbuf[3],rbuf[3];
  16. MPI_Init(&argc, &argv);
  17. MPI_Comm_size(comm, &size);
  18. MPI_Comm_rank(comm, &rank);
  19. srand(time(NULL)+rank);
  20. printf("Process %d has",rank);
  21. for(i=0;i<3;i++)
  22. {
  23. sbuf[i].val=rand()%100;
  24. sbuf[i].rank=rank; printf("%d ",sbuf[i].val);
  25. }
  26. putchar('\n');
  27. MPI_Reduce(sbuf,rbuf,3,MPI_2INT,MPI_MAXLOC,0,comm);
  28. if(rank==0)
  29. {
  30. printf("max value and location:");
  31. for(i=0;i<3;i++)
  32. printf("value=%d,location=%d\n",rbuf[i].val,rbuf[i].rank);
  33. }
  34. MPI_Finalize();
  35. return 0;
  36. }

  1. MPI_Allreduce(
  2. void* send_data,
  3. void* recv_data,
  4. int count,
  5. MPI_Datatype datatype,
  6. MPI_Op op,
  7. MPI_Comm communicator)

  1. int MPI_Scan(
  2. const void* sendbuf,
  3. void* recvbuf,
  4. int count,
  5. MPI_Datatype datatype,
  6. MPI_Op op,
  7. MPI_Comm comm)
scan例:
MPI并行编程
 
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. #include<string.h>
  5. #include<mpi.h>
  6. int main(int argc, char** argv)
  7. {
  8. MPI_Comm comm = MPI_COMM_WORLD;
  9. int size,rank,sbuf[3],rbuf[3],i;
  10. MPI_Init(&argc, &argv);
  11. MPI_Comm_size(comm, &size);
  12. MPI_Comm_rank(comm, &rank);
  13. for(i=0;i<3;i++) sbuf[i]=rank*10+i;
  14. printf("Process %d has:",rank);
  15. for(i=0;i<3;i++) printf("%d",sbuf[i]); putchar('\n');
  16. MPI_Scan(sbuf,rbuf,3,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
  17. printf("Process %d has results:",rank);
  18. for(i=0;i<3;i++)
  19. printf("%d ",rbuf[i]);
  20. putchar('\n');
  21. MPI_Finalize();
  22. return 0;
  23. }

completion、non-blockong、reduce

编译 mpicc **.c -o **

运行 mpirun -np 5 ./**                            //-machinefile nodefile your-exe-program parameters-if-any  


1.基本概念
MPI是分布式计算的基础接口架构,他有很多实现,比如intelMPI openMPI等等,而这些具体实现了这些接口里面的内容,比如一些通信协议。
 
MPI有几个很重要的概念rank, group, communicator, type, pack, spawn, window, 理解了这些概念MPI就算入门了。
 
 
group是MPI一个很重要的概念,一台电脑可以属于多个group,group的正真强大体现在可以随时随地的组合任意group,然后利用gourp内,和group间的communicator,可以很容易实现复杂科学计算的中间过程,比如奇数rank一个group,偶数另一个group,或者拓扑结构的group,这样可以解决很多复杂问题,另外MPI还有一个默认的全局的group,他就是comm world,一般简单的应用有了这一个group已经足够了。
 
rank就是任意group内的一个计算单元,利用rank我们可以很轻松的实现client server的架构,比如rank=0是server其他就是client。
 
communicator就是各种通信,比如一对一,一对多,多对一,其中多往往代表着一个group, 在传输过程中tag还是很有用的可以用来区别不同的任务类型,一般都是先解析tag,然后再解析具体的数据内容, 这里要有一个信封和信内容的差别的概念,理解了这样的差别,可以很好的扩展程序。

type是MPI的自定义类型,由于通常编程的时候常用struct 数组 和离散的变量,这些东西不能直接进行通信, 然后MPI同样有一套这样的定义,我们可以转化成MPI的格式,这样就可以很*的通信了。
 
Pack,就是把离散的数据打包起来,方便传送,其实这个作用和type很类似,如果你不想很麻烦的定义type直接打包发送。
spawn是区分MPI一代和二代的一个重要的标志,有了spawn,就可以在运行过程中自动的改变process的数量,可能复杂的软件才有这样的需求。
 
window远程的控制同一个文件,只有在网络条件很好的时候用这个才有意义,否则会让软件效率变得很糟糕。




communicator:
可被看做一组有序的进程,每个进程有一个独有的rank,是运行背景。
MPI_COMM_WORLD,默认的communicator,包含所有进程,它是MPI定义的允许程序里所有进程运行期间互相通信的通信者,或者是点对点通信,又或者是集合通信。然而对于一些应用,可能需要在选定的一个子进程组里进行通信。
通 信者有两类:内部通信者(intra-communicator)和互联通信者(inter-communicator)。内部通信者处理通信者个体里的 进程间的通信,而互联通信者处理内部通信者之间的通信。本质上来说,内部通信者是MPI_COMM_WORLD的进程的子集。我们主要专注于内部通信者。
需要新的通信者的原因经常是因为要处理矩阵的行、列或子块等需求。这些通信者通常和一个虚拟拓扑关联--比笛卡尔拓扑常用--来辅助并行操作的实现。此外,通信者的使用,经常和虚拟拓扑一起,通常增强了程序的可读性和可维护性。





并行排名:
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. #include<string.h>
  5. #include<mpi.h>
  6. #define RANDOM_MAX 20
  7. typedefstructNode{
  8. int owner;
  9. int number;
  10. }Node;
  11. void sort_node(Node*arr,int size){
  12. int i, j;
  13. for(i=0; i<size-1; i++){
  14. for(j=0; j<size-1-i; j++){
  15. if(arr[j].number > arr[j+1].number){
  16. Node t = arr[j];
  17. arr[j]= arr[j+1];
  18. arr[j+1]= t;
  19. }
  20. }
  21. }
  22. }
  23. int main(int argc,char** argv){
  24. MPI_Comm comm = MPI_COMM_WORLD;
  25. int size, rank;
  26. MPI_Init(&argc,&argv);
  27. MPI_Comm_size(comm,&size);
  28. MPI_Comm_rank(comm,&rank);
  29. int i, number,*arr_number=NULL,*sbuf=NULL, range;
  30. Node*arr_node=NULL;
  31. // srand((unsigned)time(NULL));
  32. // number = rand() % RANDOM_MAX;
  33. number = size-rank-1;
  34. if(0== rank){
  35. arr_number =(int*) malloc(sizeof(int)* size);
  36. }
  37. MPI_Gather(&number,1, MPI_INT, arr_number,1, MPI_INT,0, comm);
  38. if(0== rank){
  39. arr_node =(Node*) malloc(sizeof(Node)* size);
  40. memset(arr_node,0,sizeof(arr_node));
  41. for(i=0; i<size; i++){
  42. Node node ={i, arr_number[i]};
  43. arr_node[i]= node;
  44. }
  45. sort_node(arr_node, size);
  46. sbuf =(int*) malloc(sizeof(int)* size);
  47. memset(sbuf,0,sizeof(int));
  48. for(i=0; i<size; i++){
  49. sbuf[arr_node[i].owner]= i;
  50. }
  51. }
  52. MPI_Scatter(sbuf,1, MPI_INT,&range,1, MPI_INT,0, MPI_COMM_WORLD);
  53. printf("(process, range, number) : (%d, %d, %d)\n", rank, range, number);
  54. if(0== rank){
  55. free(arr_node);
  56. free(arr_number);
  57. free(sbuf);
  58. }
  59. MPI_Finalize();
  60. return0;
  61. }



点对点互发:

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. #include<string.h>
  5. #include<mpi.h>
  6. int main(int argc,char** argv)
  7. {
  8. int rank,size,token,source,dest;
  9. MPI_Init(&argc,&argv);
  10. MPI_Comm_size(MPI_COMM_WORLD,&size);
  11. MPI_Comm_rank(MPI_COMM_WORLD,&rank);
  12. source=rank==0?size-1:rank-1;
  13. dest=(rank+1)%size;
  14. token=100;
  15. if(rank==0){
  16. MPI_Ssend(&token,1,MPI_INT,dest,1,MPI_COMM_WORLD);
  17. printf("Process %d sends token to %d.\n",rank,dest);
  18. MPI_Recv(&token,1,MPI_INT,source,1,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
  19. printf("Process %d receives token from %d.\n",rank,source);
  20. }
  21. else{
  22. MPI_Recv(&token,1,MPI_INT,source,1,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
  23. printf("Process %d receives token from %d.\n",rank,source);
  24. MPI_Ssend(&token,1,MPI_INT,dest,1,MPI_COMM_WORLD);
  25. printf("Process %d sends token to %d.\n",rank,dest);
  26. }
  27. MPI_Finalize();
  28. return0;
  29. }

积分:
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<time.h>
  4. #include<math.h>
  5. #include<mpi.h>
  6. #define PI 3.14159265358979
  7. #define ROOT 0
  8. int main(int argc,char** argv){
  9. time_t s=0, e=0;///时间统计
  10. ///MPI初始化
  11. MPI_Comm comm = MPI_COMM_WORLD;
  12. int size, rank;
  13. MPI_Init(&argc,&argv);
  14. MPI_Comm_size(comm,&size);
  15. MPI_Comm_rank(comm,&rank);
  16. int j;
  17. double a=0, b=100*PI;///区间,单位为弧度
  18. double*arr_res=NULL;///保存计算结果数组
  19. double part_len=(b-a)/size;///每一小段的长度
  20. double sum_local=0, sum=0;///每一进程的计算结果和最终计算结果
  21. double width=0.000001;///每一小段的宽度,即计算精度
  22. ///在根进程中申请结果数组
  23. if(ROOT == rank){
  24. s = clock();
  25. arr_res =(double*) malloc(sizeof(double)*size);
  26. }
  27. ///每一段求积分
  28. double begin=rank*part_len, end=(rank+1)*part_len;
  29. for(; begin<end; begin+=width){
  30. sum_local += fabs(cos(begin)*width);
  31. // sum_local += cos(begin)*width;
  32. }
  33. ///打印每一段的积分结果
  34. printf("Process %d integrate is : %lf\n", rank, sum_local);
  35. ///每一段将积分结果发到根进程
  36. MPI_Gather(&sum_local,1, MPI_DOUBLE, arr_res,1, MPI_DOUBLE, ROOT, comm);
  37. ///根进程计算最终结果
  38. if(ROOT == rank){
  39. for(j=0; j<size; j++)
  40. sum += arr_res[j];
  41. printf("cos(x) integarte is %lf\n", sum);
  42. free(arr_res);
  43. e = clock();
  44. printf("time: %ldms\n",(e-s)/1000);
  45. }
  46. ///MPI结束
  47. MPI_Finalize();
  48. return0;
  49. }


maximum:


average:

  1. // Creates an array of random numbers. Each number has a value from 0 - 1
  2. float*create_rand_nums(int num_elements){
  3. float*rand_nums =(float*)malloc(sizeof(float)* num_elements);
  4. assert(rand_nums != NULL);
  5. int i;
  6. for(i =0; i < num_elements; i++){
  7. rand_nums[i]=(rand()/(float)RAND_MAX);
  8. }
  9. return rand_nums;
  10. }
  1. // Computes the average of an array of numbers
  2. float compute_avg(float*array,int num_elements){
  3. float sum =0.f;
  4. int i;
  5. for(i =0; i < num_elements; i++){
  6. sum += array[i];
  7. }
  8. return sum / num_elements;
  9. }
  1. int main(int argc,char** argv){
  2. if(argc !=2){
  3. fprintf(stderr,"Usage: avg num_elements_per_proc\n");
  4. exit(1);
  5. }
  6. int num_elements_per_proc = atoi(argv[1]);
  7. srand(time(NULL));
  8. MPI_Init(NULL, NULL);
  9. int world_rank;
  10. MPI_Comm_rank(MPI_COMM_WORLD,&world_rank);
  11. int world_size;
  12. MPI_Comm_size(MPI_COMM_WORLD,&world_size);
  1. float*rand_nums = NULL;
  2. if(world_rank ==0){
  3. rand_nums = create_rand_nums(num_elements_per_proc * world_size);
  4. }
  5. float*sub_rand_nums =(float*)malloc(sizeof(float)*
  6. num_elements_per_proc);
  7. assert(sub_rand_nums != NULL);
  8. MPI_Scatter(rand_nums, num_elements_per_proc, MPI_FLOAT,
  9. sub_rand_nums, num_elements_per_proc, MPI_FLOAT,
  10. 0, MPI_COMM_WORLD);
  1. float sub_avg = compute_avg(sub_rand_nums,
  2. num_elements_per_proc);
  3. float*sub_avgs = NULL;
  4. if(world_rank ==0){
  5. sub_avgs =(float*)malloc(sizeof(float)* world_size);
  6. assert(sub_avgs != NULL);
  7. }
  8. MPI_Gather(&sub_avg,1, MPI_FLOAT, sub_avgs,1,
  9. MPI_FLOAT,0, MPI_COMM_WORLD);
  10. if(world_rank ==0){
  11. float avg = compute_avg(sub_avgs, world_size);
  12. printf("Avg of all elements is %f\n", avg);
  13. float original_data_avg =
  14. compute_avg(rand_nums, num_elements_per_proc * world_size);
  15. printf("Avg computed across original data is %f\n", original_data_avg);
  16. }
  17. if(world_rank ==0){
  18. free(rand_nums);
  19. free(sub_avgs);
  20. }
  21. free(sub_rand_nums);
  22. MPI_Barrier(MPI_COMM_WORLD);
  23. MPI_Finalize();
  24. }



矩阵乘法:
法1
  1. #include<stdlib.h>
  2. #include<stdio.h>
  3. #include<time.h>
  4. #include<mpi.h>
  5. #define R1 1000
  6. #define C1 1000
  7. #define R2 1000
  8. #define C2 1000
  9. #define ROOT 0
  10. void print_(int*);///输出结果
  11. void format(int*,int*,int);///格式化结果
  12. void save_to_file(int*);///保存到文件
  13. int main(int argc,char** argv){
  14. time_t s=0, e=0;
  15. MPI_Comm comm = MPI_COMM_WORLD;
  16. int size, rank;
  17. MPI_Init(&argc,&argv);
  18. MPI_Comm_size(comm,&size);
  19. MPI_Comm_rank(comm,&rank);
  20. int i, j, k, count;
  21. int matrix1[R1][C1];
  22. int each_col = C2 / size;///每个进程有 C2/size列
  23. int column[each_col][R2];///分配给每一个进程 有each_col行,R2列,转置以后的
  24. int*matrix2=NULL;///矩阵2
  25. int*rbuf=NULL;///存储计算结果
  26. int*rbuf1=NULL;///存储最终结果
  27. ///给第一个矩阵设置值
  28. count =1;
  29. for(i=0; i<R1; i++){
  30. for(j=0; j<C1; j++){
  31. matrix1[i][j]= count;
  32. }
  33. }
  34. if(rank == ROOT){
  35. s = clock();
  36. ///第二个矩阵申请内存
  37. matrix2 =(int*)malloc(sizeof(int)*R2*C2);
  38. ///第二个设置值
  39. count=1;
  40. for(i=0; i<R2*C2; i++){
  41. matrix2[i]=count;
  42. }
  43. ///申请内存
  44. rbuf =(int*) malloc(sizeof(int)*R1*C2);
  45. rbuf1 =(int*) malloc(sizeof(int)*R1*C2);
  46. }
  47. MPI_Scatter(matrix2, R2*each_col , MPI_INT, column, R2*each_col, MPI_INT, ROOT, comm);
  48. //执行矩阵乘法
  49. int result[R1][each_col];
  50. for(i=0; i<R1; i++){
  51. for(j=0; j<each_col; j++){
  52. result[i][j]=0;
  53. for(k=0; k<C1; k++){
  54. result[i][j]+= matrix1[i][k]*column[j][k];
  55. }
  56. }
  57. }
  58. MPI_Gather(result, R1*each_col, MPI_INT, rbuf, R1*each_col, MPI_INT, ROOT, comm);
  59. if(ROOT == rank){
  60. ///转置,使结果格式化
  61. format(rbuf, rbuf1, each_col);
  62. ///打印结果到屏幕
  63. ///print_(rbuf1);
  64. ///输出结果到文件
  65. save_to_file(rbuf1);
  66. free(matrix2);
  67. free(rbuf);
  68. free(rbuf1);
  69. e = clock();
  70. printf("time: %ld ms\n",(e-s)/1000);
  71. }
  72. MPI_Finalize();
  73. return0;
  74. }
  75. void save_to_file(int* rbuf1){
  76. int i, j;
  77. FILE*fpt;
  78. fpt = fopen("out1","w");
  79. for(i=0; i<R1; i++){
  80. fprintf(fpt,"%d", rbuf1[i*C2]);
  81. for(j=1; j<C2; j++)
  82. fprintf(fpt," %d", rbuf1[i*C2+j]);
  83. fprintf(fpt,"\n");
  84. }
  85. fclose(fpt);
  86. }
  87. void format(int* rbuf,int* rbuf1,int each_col){
  88. int count =0, i, j, k;
  89. for(i=0; i<R1; i+=each_col){
  90. for(k=0; k<R1; k++){
  91. for(j=i; j<i+each_col; j++){
  92. rbuf1[k*R1+j]= rbuf[count++];
  93. }
  94. }
  95. }
  96. }
  97. void print_(int* rbuf1){
  98. int i, j;
  99. for(i=0; i<R1; i++){
  100. for(j=0; j<C2; j++){
  101. printf("%d ", rbuf1[i*C2+j]);
  102. }
  103. printf("\n");
  104. }
  105. }



上一篇: 不等式

下一篇: 货仓选址