#include<stdio.h>
#include<mpi.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
int main(int argc,char*argv[])
{
int rank,numProcs;//进程的有关变量
MPI_Status status;
int n = 100,l = 200,m = 100;//定义A,B矩阵的行和列
int lineSize = 0;//记录矩阵A分配到每个进程的行数(一个块)
double *B = (double *)malloc(sizeof(double) * l * m);//矩阵B
double *ABuffer = (double *)malloc(sizeof(double) * lineSize * l);//A的发送与接受块
double *CRecv = (double *)malloc(sizeof(double) * lineSize * m);//C的发送与接受块
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&numProcs);
lineSize = floor((double)n / (numProcs-1));
if(0 == rank){
double *A = (double *)malloc(sizeof(double) * n * l);//矩阵A
double *C = (double *)malloc(sizeof(double) * n * m);//矩阵B
//创建A,B数据
srand(time(NULL));
for(int i = 0 ; i < n ;i++)
for(int j = 0;j < l;j++)
A[i * l + j] = rand() % 6;
for(int i = 0 ; i < l ;i++)
for(int j = 0;j < m;j++)
B[i * m + j] = rand() % 6;
//以块分发A
int ASendBegin = 0;
for(int id = 1;id < numProcs;id++){
for(int i = 0;i < lineSize * l;i++)
ABuffer[i] = A[ASendBegin + i];
MPI_Send(ABuffer,lineSize * l,MPI_DOUBLE,id,2,MPI_COMM_WORLD);
ASendBegin += lineSize * l;
}
//整体分发B
for(int id = 1; id < numProcs;id++)
MPI_Send(B,6,MPI_DOUBLE,id,1,MPI_COMM_WORLD);
//接受数据并且拼接数据
int CBegin = 0;
for(int id = 1;id < numProcs;id++){
MPI_Recv(CRecv,lineSize*m,MPI_DOUBLE,id,3,MPI_COMM_WORLD,&status);
//填数
for(int i = 0 ; i < lineSize * m ;i++){
C[CBegin++] = CRecv[i];
}
}
//对A剩余数据进行处理
while(ASendBegin < n * l){
double *t = (double *)malloc(sizeof(double) * l);
for(int i = 0;i < l;i++){
t[i] = A[ASendBegin + i];
}
//comput
for(int j = 0 ; j < m;j++){
for(int k = 0;k < l;k++){
C[CBegin] += t[k]* B[k*m + j];
}
CBegin++;
}
ASendBegin += l;
free(t);
}
printf("rank is %d\n",rank);
//打印A矩阵数据
printf("A矩阵如下:\n");
for(int i = 0 ; i < n ;i ++){
for(int j = 0 ; j < l;j++)
printf("%lf ",A[i * l + j]);
printf("\n");
}
//printf("\n");
//打印B矩阵
printf("B矩阵如下\n");
for(int i = 0 ; i < l ;i ++){
for(int j = 0 ; j < m;j++)
printf("%lf ",B[i * m + j]);
printf("\n");
}
//printf("\n");
//打印C矩阵
printf("C矩阵如下\n");
for(int i = 0 ; i < n ;i ++){
for(int j = 0 ; j < m;j++)
printf("%lf ",C[i * m + j]);
printf("\n");
}
printf("\n");
//释放申请空间
//free(A);free(C);
}else{
//接受B矩阵数组
MPI_Recv(B,l * m,MPI_DOUBLE,0,1,MPI_COMM_WORLD,&status);
//接受A块数据
MPI_Recv(ABuffer,lineSize * l,MPI_DOUBLE,0,2,MPI_COMM_WORLD,&status);
//进行CRecv的初始化
for(int i = 0;i < lineSize * m;i++)
CRecv[i] = 0;
//计算矩阵乘法结果
for(int i = 0;i < lineSize;i++){
for(int j = 0 ; j < m ;j++){
for(int k = 0 ; k < l ;k++){
CRecv[i * m + j] += ABuffer[i * l + k] * B[k * m + j];
}
}
}
//结果发送给主进程
MPI_Send(CRecv,lineSize * m,MPI_DOUBLE,0,3,MPI_COMM_WORLD);
}
MPI_Finalize();
return 0;
}