1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| #include<iostream> #include <mpi.h> #include<algorithm> using namespace std; const int MAX_size=1e7; int get_state(int myid){ if(myid==0)return 1; else if(myid<3)return 0; else return -1; } int main(int argc, char* argv[]) { int numprocs, myid, source; MPI_Status status; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &myid); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); int state=get_state(myid); if(state==1){ int* nums=new int[MAX_size+3]; int son1=(myid<<1)+1,son2=(myid<<1)+2; for(int i=0;i<MAX_size;i++)nums[i]=rand(); int t1=clock(); MPI_Send(nums,MAX_size/2,MPI_INT,son1,myid*numprocs+son1,MPI_COMM_WORLD); MPI_Send(nums+MAX_size/2,MAX_size/2,MPI_INT,son2,myid*numprocs+son2,MPI_COMM_WORLD); int* rec1=new int[MAX_size/2+3],*rec2=new int[MAX_size/2+3]; MPI_Recv(rec1,MAX_size/2,MPI_INT,son1,myid*numprocs+son1,MPI_COMM_WORLD,&status); MPI_Recv(rec2,MAX_size/2,MPI_INT,son2,myid*numprocs+son2,MPI_COMM_WORLD,&status); int i=0,j=0,size=MAX_size/2,loc=0; while(i<size&&j<size){ if(rec1[i]<rec2[j]){ nums[loc++]=rec1[i++]; } else{ nums[loc++]=rec2[j++]; } } while(i<size){nums[loc++]=rec1[i++];} while(j<size){nums[loc++]=rec2[j++];}
int t2=clock(); cout<<t2-t1<<endl; }
else if(state==0){ int* nums=new int[MAX_size/2+3]; int* rec1=new int[MAX_size/4+3],*rec2=new int[MAX_size/4+3]; int son1=(myid<<1)+1,son2=(myid<<1)+2,fa=(myid-1)>>1; MPI_Recv(nums,MAX_size/2,MPI_INT,fa,fa*numprocs+myid,MPI_COMM_WORLD,&status); MPI_Send(nums,MAX_size/4,MPI_INT,son1,myid*numprocs+son1,MPI_COMM_WORLD); MPI_Send(nums+MAX_size/4,MAX_size/4,MPI_INT,son2,myid*numprocs+son2,MPI_COMM_WORLD); MPI_Recv(rec1,MAX_size/4,MPI_INT,son1,myid*numprocs+son1,MPI_COMM_WORLD,&status); MPI_Recv(rec2,MAX_size/4,MPI_INT,son2,myid*numprocs+son2,MPI_COMM_WORLD,&status); int i=0,j=0,size=MAX_size/4,loc=0; while(i<size&&j<size){ if(rec1[i]<rec2[j]){ nums[loc++]=rec1[i++]; } else{ nums[loc++]=rec2[j++]; } } while(i<size){nums[loc++]=rec1[i++];} while(j<size){nums[loc++]=rec2[j++];} MPI_Send(nums,MAX_size/2,MPI_INT,fa,fa*numprocs+myid,MPI_COMM_WORLD); }
else{ int* nums=new int[MAX_size/4+3]; int fa=(myid-1)>>1; MPI_Recv(nums,MAX_size/4,MPI_INT,fa,fa*numprocs+myid,MPI_COMM_WORLD,&status);
sort(nums,nums+MAX_size/4); MPI_Send(nums,MAX_size/4,MPI_INT,fa,fa*numprocs+myid,MPI_COMM_WORLD); }
MPI_Finalize(); }
|