gpt4 book ai didi

c - 使用 MPI_Gather 断言失败

转载 作者:行者123 更新时间:2023-11-30 16:50:54 26 4
gpt4 key购买 nike

我正在尝试编写 MPI C 代码,该代码重复执行计算并将其结果保存到单个数组中,以降低输出频率。下面的示例代码(var 的大小,200,足以满足正在使用的 CPU 数量):

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>

int main(int argc, char **argv){

float *phie, *phitemp, var[200];
int time=0, gatherphi=10, gatherfile = 200, j, iter=0, lephie, x;
int nelecrank = 2, size, rank, Tmax = 2000;
FILE *out;

MPI_Init(&argc, &argv) ;

MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);

lephie = gatherfile/gatherphi; // number of runs of calculation before output

// allocate memory
//printf("%d Before malloc.\n", rank);
if (rank==1) phie=(float *) malloc(nelecrank*size*gatherfile/gatherphi*sizeof(float));
phitemp=(float *) malloc(nelecrank*sizeof(float));
//printf("%d After malloc.\n", rank);

for(j=0;j<200;j++) var[j]=rank;

for(time=0;time<Tmax;time++){
if (!time%gatherphi) {// do calculation

for (j=0;j<nelecrank;j++) { // each processor does the calculation nelecrank times
phitemp[j]=0;
for (x = 0; x<=4; x++) {
phitemp[j]=phitemp[j]+var[rank+j*size];
}
}
} // end of j for loop
printf("iter: %d, %d Before MPI_Gather.\n", iter, rank);
MPI_Gather(phitemp, nelecrank, MPI_FLOAT, phie+iter*nelecrank*size*sizeof(float), nelecrank, MPI_FLOAT, 1, MPI_COMM_WORLD);
iter++;
} // end of gatherphi condition

if (time % gatherfile) { //output result of calculation
iter=0;
if (rank==1) {
out = fopen ("output.txt", "wt+");
if (out == NULL) {
printf("Could not open output file.\n");
exit(1);
}
else printf("Have opened output file.\n");
for (j=0;j<nelecrank*size*lephie;j++) {
fprintf(out,"%f ",*(phie+j*sizeof(float)));
}
fclose(out);
}
} // end of file output

if (rank==1) {
if (phie) free (phie);
}
if (phitemp) free (phitemp);
MPI_Finalize();

return 0;
}

它给我带来了重复的内存分配问题,直到它最终退出。我没有在 MPI 中使用内存分配的经验 - 你能帮忙吗?

非常感谢,玛尔塔

最佳答案

基本上,phie 不够大。

mallocphie分配了nelecrank*size*gatherfile/gatherphi*sizeof(float)=80*sizeof(float)内存。

但是,您的 MPI_Gather 使用需要 iter*nelecrank*size*sizeof(float)+nelecrank*size*sizeof(float) 内存。 iter 的最大值为 nelecrank*Tmax-1,因此 phie 需要为 (nelecrank*Tmax-1)*nelecrank *size*sizeof(float)+nelecrank*size*sizeof(float),大约是 8000*size*sizeof(float) 大。

也许您想在循环中的某个位置重置 iter=0

关于c - 使用 MPI_Gather 断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41983839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com