matrix1

//Writed by YaoPu, Oct 10,2016
//connect via Email:yaopu@iccas.ac.cn
#include"mpi.h"
#include"stdio.h"
#include<stdlib.h>
const int rows = 400; //the rows of matrix
const int cols = 100; //the cols of matrix
int main(int argc, char **argv)
{
int i,j,k,myid,numprocs,anstag;
int A[rows][cols],B[cols],C[rows];
int masterpro,buf[cols],ans,cnt;
double starttime,endtime;
double tmp,totaltime;
MPI_Status status;
masterpro = 0;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
for(cnt=0;cnt<10;cnt++)
{
if(numprocs<2){
printf("Error:Too few processors!\n");
MPI_Abort(MPI_COMM_WORLD,99);
}

if (myid==masterpro){
starttime = MPI_Wtime();
for(i=0;i<cols;i++)
{
B[i]=rand()%10;
for(j=0;j<rows;j++)
{
A[j][i]=rand()%10;
}
}
//bcast the B vector to all slave processors
MPI_Bcast(B,cols,MPI_INT,masterpro,MPI_COMM_WORLD);
//partition the A matrix to all slave processors
for(i=1;i<numprocs;i++)
{
for(k=i-1;k<rows;k+=numprocs-1)
{
for(j=0;j<cols;j++)
{
buf[j]=A[k][j];
}
MPI_Send(buf,cols,MPI_INT,i,k,MPI_COMM_WORLD);
}
}
}
else{
//starttime = MPI_Wtime();
MPI_Bcast(B,cols,MPI_INT,masterpro,MPI_COMM_WORLD);
//every processors receive the part of A matrix, and make Mul Operator with B vector
for(i= myid-1;i<rows;i+=numprocs-1){
MPI_Recv(buf,cols,MPI_INT,masterpro,i,MPI_COMM_WORLD,&status);
ans=0;
for(j=0;j<cols;j++)
{
ans=buf[j]*B[j];
}
MPI_Send(&ans,1,MPI_INT,masterpro,i,MPI_COMM_WORLD);
}
//endtime = MPI_Wtime();
//tmp = endtime-starttime;
}
if(myid==masterpro){
//receive the result from all slave processor
for(i=0;i<rows;i++)
{
MPI_Recv(&ans,1,MPI_INT,MPI_ANY_SOURCE,MPI_ANY_TAG,MPI_COMM_WORLD,&status);
//sender = status.MPI_RESOURCE;
anstag = status.MPI_TAG;
C[anstag] =ans;
}
//print result 
/* for (i=0;i<rows;i++)
{
printf("%d",C[i]);
if((i+1)%20==0)
printf("\n");
}
*/
}
}
endtime = MPI_Wtime();
totaltime= endtime - starttime;
if (myid == masterpro)
printf("total time :%f s.\n",totaltime);
MPI_Finalize();
return 0;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值