我是 MPI 的新手,并将其作为大学课程进行学习。任务是使用和以数字方式找到 const e的值。我找到的唯一合适的方法是MPI_Send()
MPI_Recv()
我在 2、3 和 4 核上运行它,但得到了错误的数字,而在 1 核上一切正常。这是我的代码:
#include <iostream>
#include <fstream>
#include <cmath>
#include "mpi.h"
using namespace std;
const int n = 1e04;
double start_time, _time;
int w_size, w_rank, name_len;
char cpu_name[MPI_MAX_PROCESSOR_NAME];
ofstream fout("exp_result", std::ios_base::app | std::ios_base::out);
long double factorial(int num){
if (num < 1)
return 1;
else
return num * factorial(num - 1);
}
void e_finder(){
long double sum = 0.0, e = 0.0;
if(w_rank == 0)
start_time = MPI_Wtime();
for(int i = 0; i < n; i+=w_size)
sum += 1.0 / factorial(i);
MPI_Send(&sum, 1, MPI_LONG_DOUBLE, 0, 0, MPI_COMM_WORLD);
if(w_rank == 0){
// e += sum;
for (int i = 0; i < w_size; i++){
MPI_Recv(&sum, 1, MPI_LONG_DOUBLE, i, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
e += sum;
}
_time = MPI_Wtime() - start_time;
cout.precision(29);
cout << "e = "<< e << endl << fixed << "error is " << abs(e - M_E) << endl;
cout.precision(9);
cout << "\nwall clock time = " <<_time << " sec\n";
fout << w_size << "\t" << _time << endl;
}
}
int main(int argc, char const *argv[]) {
MPI_Init(NULL, NULL);
MPI_Comm_size(MPI_COMM_WORLD, &w_size);
MPI_Comm_rank(MPI_COMM_WORLD, &w_rank);
MPI_Get_processor_name(cpu_name, &name_len);
cout<<"calculations started on cpu:" << w_rank << "!\n";
MPI_Barrier(MPI_COMM_WORLD);
e_finder();
MPI_Finalize();
fout.close();
return 0;
}
有人可以帮我找出并掌握错误吗?以下是输出:
$ mpirun -np 1 ./exp1
calculations started on cpu:0!
e = 2.718281828459045235428168108
error is 0.00000000000000014463256980957
wall clock time = 4.370553009 sec
$ mpirun -np 2 ./exp1
calculations started on cpu:0!
calculations started on cpu:1!
e = 3.0861612696304875570925407846
error is 0.36787944117144246629694248618
wall clock time = 2.449338411 sec
$ mpirun -np 3 ./exp1
calculations started on cpu:0!
calculations started on cpu:1!
calculations started on cpu:2!
e = 3.5041749401277555767651727958
error is 0.78589311166871048596957449739
wall clock time = 2.011082204 sec
$ mpirun -np 4 ./exp1
calculations started on cpu:0!
calculations started on cpu:3!
calculations started on cpu:1!
calculations started on cpu:2!
e = 4.1667658813667669917037150729
error is 1.44848405290772190090811677443
wall clock time = 1.617427335 sec
问题在于你如何划分工作。似乎您希望每个程序计算分数的一部分。但是,它们都是从第一个分数开始,然后计算每个w_size
分数。这会导致某些分数被多次计算,而有些分数根本不会被计算。这应该通过更改行来解决
for(int i = 0; i < n; i+=w_size)
到
for(int i = w_rank; i < n; i+=w_size)
这使得每个程序以不同的分数开始,并且由于它们正在计算每个w_size
分数,因此计算的分数之间不应再有任何冲突。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句