【发布时间】:2026-02-09 19:25:01
【问题描述】:
伙计们!我写了一个代码,用 MPI 计算两个巨大向量的标量积。 首先,秩为 0 的进程创建两个随机向量,并通过 MPI_Scatter 将其发送给其余的。之后,他们计算他们的部分总和并将其发送回等级为 0 的进程。 主要问题是 MPI_Scatter 需要花费大量时间将数据发送到其他进程,因此我的程序会因其他进程而变慢。我用 MPI_Wtime() 测量了它,而 MPI_Scatter() 函数在某些情况下占用了 80% 的计算时间。 我的串行代码比我尝试过的任何 MPI 设置都快。
这些是我在具有不同进程数量的双核上的结果:
处理时间
序列号 0,3275
1 0,3453
2 0,4522
4 3,4755
8 5,8645
10 8,9112
20 24,4612
40 63,2633
您知道如何避免此类瓶颈吗? 不要介意 MPI_Allgather()... 这是作业的一部分 :)
int main(int argc, char* argv[])
{
srand(time(NULL));
int size, len, whoAmI, i, j, k;
int N = 10000000;
double start, elapsed_time, end;
double *Vec1, *Vec2;
MPI_Init(&argc, &argv);
start = MPI_Wtime();
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &whoAmI);
if(N%size != 0){
printf("choose a number that can be divided through 10000000\n");
exit(1);
}
int chunk = N/size;
double *buf1 = malloc(chunk * sizeof(double)); // Recv_Buf for MPI_scatter
double *buf2 = malloc(chunk * sizeof(double));
double *gatherResult = malloc(size*(sizeof(double))); //Recv_Buf for MPI_Allgather
double result, FinalResult = 0;
if(whoAmI == 0){
Vec1 = malloc(N * sizeof(double));
Vec2 = malloc(N * sizeof(double));
random_Vector(Vec1, N);
random_Vector(Vec2, N);
}
/* sends the divided array to the other processes */
MPI_Scatter(Vec1, chunk, MPI_DOUBLE, buf1, chunk, MPI_DOUBLE, 0, MPI_COMM_WORLD);
MPI_Scatter(Vec2, chunk, MPI_DOUBLE, buf2, chunk, MPI_DOUBLE, 0, MPI_COMM_WORLD);
if(whoAmI == 0){
end = MPI_Wtime();
elapsed_time = end - start;
printf("Time taken %.4f seconds\n", elapsed_time);
}
for(i = 0; i < chunk; i ++){
result += buf1[i] * buf2[i];
}
printf("The sub result: #%d, %.2f\n",whoAmI, result);
/* Allgather: (sendBuf, number of Elements in SendBuf, Type of Send, Number of Elements Recv, Recv Type, Comm)*/
MPI_Allgather(&result, 1 , MPI_DOUBLE, gatherResult, 1, MPI_DOUBLE , MPI_COMM_WORLD);
for(i = 0; i < size; i++){
FinalResult += gatherResult[i];
}
MPI_Barrier(MPI_COMM_WORLD);
end = MPI_Wtime();
elapsed_time = end - start;
if(whoAmI == 0){
printf("FinalResult is: %.2f\n", FinalResult);
printf("Time taken %.4f seconds\n", elapsed_time);
VecVec_Test(N, Vec1, Vec2, FinalResult); // Test if the Result is correct
}
MPI_Barrier(MPI_COMM_WORLD);
return 0;
}
【问题讨论】:
-
您分发的是一个非常琐碎的过程,所以我并不感到惊讶。为什么您会期望序列化、反序列化和网络开销比将两个数字相乘更便宜?
-
好吧,我正在计算一个包含 10000000 个条目的向量乘法,所以并行化没有意义吗?但不知何故,分散函数比并行乘法的好处更能减慢代码速度。
-
您真的不希望在双核 CPU 上使用 40 个 MPI 进程来加速,是吗?!
-
这只是一个测试,表明由于分散功能,更多的进程需要更多的时间。数据输出应该都是一样的,因为 scatter 会砍掉数组。如您所见,2 个进程也不比 1 个更快。
标签: c++ c parallel-processing mpi