矩阵相乘的并行算法的设计与实现

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

仲恺农业工程学院实验报告纸

计算机科学与工程学院(院、系)网络工程专业083 班组并行计算应用试验课

学号:200810224311 姓名:李志冬实验日期:2011-05-19 教师评定实验三矩阵相乘的并行算法的设计与实现

一、实验目的

理解和掌握矩阵相乘的并行算法的设计思想以及实现原理

二、实验内容

编译和运行一个两矩阵相乘算法的并行程序

三、实验步骤

1 使用vi编辑器输入并行计算的代码,保存在multi.c中

#include

#include "mpi.h"

#define NRA 62

#define NCA 15

#define NCB 7

#define MASTER 0

#define FROM_MASTER 1

#define FROM_WORKER 2

MPI_Status status;

int main(int argc, char *argv[])

{

int numtasks,

taskid,

numworkers,

source,

dest,

nbytes,

mtype,

dbsize,

rows,

averow,extra,offset,

i,j,k,

count;

double a[NRA][NCA],b[NCA][NCB],c[NRA][NCB];

intsize = sizeof(int);

dbsize = sizeof(double);

MPI_Init(&argc,&argv);

MPI_Comm_rank(MPI_COMM_WORLD,&taskid);

MPI_Comm_size(MPI_COMM_WORLD,&numtasks);

numworkers = numtasks-1;

if(taskid==MASTER) {

printf("Number of worker tasks = %d\n",numworkers);

for(i=0;i

for(j=0;j

a[i][j]=i+j;

for(i=0;i

for(j=0;j

b[i][j]=i*j;

averow=NRA/numworkers;

extra=NRA%numworkers;

offset=0;

mtype=FROM_MASTER;

for(dest=1;dest<=numworkers;dest++) {

rows=(dest<=extra)?averow+1:averow;

printf("sending %d rows to task %d\n",rows,dest);

MPI_Send(&offset,1,MPI_INT,dest,mtype,MPI_COMM_WORLD);

MPI_Send(&rows,1,MPI_INT,dest,mtype,MPI_COMM_WORLD);

count=rows*NCA;

MPI_Send(&a[offset][0],count,MPI_DOUBLE,dest,mtype,MPI_COMM_WORLD);

count=NCA*NCB;

MPI_Send(&b,count,MPI_DOUBLE,dest,mtype,MPI_COMM_WORLD);

offset=offset+rows;

}

mtype=FROM_WORKER;

for(i=1;i<=numworkers;i++) {

source = i;

MPI_Recv(&offset,1,MPI_INT,source,mtype,MPI_COMM_WORLD,&status);

MPI_Recv(&rows,1,MPI_INT,source,mtype,MPI_COMM_WORLD,&status);

count=rows*NCB;

atus);

}

printf("Here is the result matrix\n");

for(i=0;i

printf("\n");

for(j=0;j

printf("%6.2f ",c[i][j]);

}

printf("\n");

}

if(taskid>MASTER) {

mtype=FROM_MASTER;

source=MASTER;

printf("Master=%d,mtype=%d\n",source,mtype);

MPI_Recv(&offset,1,MPI_INT,source,mtype,MPI_COMM_WORLD,&status);

printf("offset=%d\n",offset);

MPI_Recv(&rows,1,MPI_INT,source,mtype,MPI_COMM_WORLD,&status);

printf("rows=%d\n",rows);

count=rows*NCA;

MPI_Recv(&a,count,MPI_DOUBLE,source,mtype,MPI_COMM_WORLD,&status);

printf("a[0][0]=%e\n",a[0][0]);

count=NCA*NCB;

MPI_Recv(&b,count,MPI_DOUBLE,source,mtype,MPI_COMM_WORLD,&status);

printf("b=\n");

for(k=0;k

for(i=0;i

c[i][k]=0.0;

for(j=0;j

c[i][k]=c[i][k]+a[i][j]*b[j][k];

}

mtype=FROM_WORKER;

printf("after computer\n");

MPI_Send(&offset,1,MPI_INT,MASTER,mtype,MPI_COMM_WORLD);

MPI_Send(&rows,1,MPI_INT,MASTER,mtype,MPI_COMM_WORLD);

MPI_Send(&c,rows*NCB,MPI_DOUBLE,MASTER,mtype,MPI_COMM_WORLD);

printf("after send\n");

}

MPI_Finalize();

return 0;

}

2 编译multi.c

相关文档
最新文档