转载请注明出处。
/*
Function:C++实现并行矩阵乘法;
Time: 19/03/25;
Writer:ZhiHong Cc;
*/
运行方法:切到工程文件x64\Debug文件下,打开命令行,输入以下指令:
mpiexec -n N Project.exe NUM
// N代表开启进程数量,NUM代表矩阵规模大小(size)
具体代码:
1.头文件:
#include
#include
#include
#include
#include
2.矩阵规模(size)接收,通过C++自带参数argv和argc[ ]:
if (argv == 2)
{
//判断有无矩阵大小size接收,无则初始化为5
size = atoi(argc[1]);
}
else { size = 5; }
3.为各指针变量分配空间
int *a, *b, *c, *pce, *ans;
a = (int*)malloc(sizeof(int)*size*size);//矩阵a
b = (int*)malloc(sizeof(int)*size*size);//矩阵b
c = (int*)malloc(sizeof(int)*size*size);//结果矩阵
pce = (int*)malloc(sizeof(int)*size*line);//接收a矩阵下的块矩阵
ans = (int*)malloc(sizeof(int)*size*line);//暂存次进程的答案
4.定义进程号,进程个数以及块矩阵的行数
int rank, numprocess, line;
line = size / numprocess;//将数据分为(进程数)个块,主进程也要处理数据
5.主进程中进行一系列操作:生成矩阵、分配矩阵、接收次进程答案、拼接答案、计算耗时、最终输出三个矩阵
for (int i = 0; i
{