使用MPI在C ++中实现矩阵乘法

问题描述

我应该修改一个执行矩阵加法的c ++ mpi程序来执行矩阵乘法。看起来像是一个简单的修改,但没有用。

void head(int num_processes){

init(A,SZ,true),init(B,init(C,false);

print(A,SZ);
print(B,SZ);

//my plan is to scatter A based on number of processes and broadcast B to all nodes
int num_rows_per_process_from_A = SZ / num_processes;
int num_elements_to_bcast = (SZ * SZ);
int num_elements_to_scatter_or_gather = (SZ * SZ) / num_processes;


MPI_Scatter(&A[0][0],num_elements_to_scatter_or_gather,MPI_INT,&A,MPI_COMM_WORLD);
MPI_Bcast(&B[0][0],num_elements_to_bcast,MPI_COMM_WORLD);


for(long i = 0; i < num_rows_per_process_from_A; ++i) //takes into account the rows
{
    for(long j = 0; j < SZ; ++j) //columns
    {
        for(long k = 0; k < SZ; ++k) //columns
        {
            C[i][j] += A[i][k] * B[k][j];
        }
    }
}

MPI_Gather(MPI_IN_PLACE,&C[0][0],MPI_COMM_WORLD);
//send the results back to the head node for merging and printing

print(C,SZ);}

void node(int process_rank,int num_processes){
int num_rows_per_process_from_A = SZ / num_processes;
int num_elements_to_bcast = (SZ * SZ);
int num_elements_to_scatter_or_gather = (SZ * SZ) / num_processes;

//receive my rows of matrix A,and all B
init(A,num_rows_per_process_from_A,false),false);

MPI_Scatter(NULL,&A[0][0],MPI_COMM_WORLD);


//calculate the assigned rows of matrix C

for(long i = 0; i < num_rows_per_process_from_A; ++i) //takes into account the rows
{
    for(long j = 0; j < SZ; ++j) //columns
    {
        for(long k = 0; k < SZ; ++k) //columns
        {
            C[i][j] += A[i][k] * B[k][j];
        }
    }
}

MPI_Gather(&C[0][0],NULL,MPI_COMM_WORLD);}

加法程序正常工作,我唯一修改的就是将加法代码替换为

for(long i = 0; i < num_rows_per_process_from_A; ++i) {
for(long j = 0; j < SZ; ++j) //columns
{
    for(long k = 0; k < SZ; ++k) //columns
    {
        C[i][j] += A[i][k] * B[k][j];
    }
} }
头和节点功能中的

。我认为我在计算节点功能时犯了一个错误,但我不确定如何确定。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)