c++ - 使用 mpi 的谐波和:开始使用 mpi 时遇到问题,不确定如何将其修改为谐波级数
问题描述
我是使用 MPI 的新手,我正在尝试修改此代码以执行 n = 20 的谐波系列,但我不太确定如何开始。MPI 究竟是如何工作的,我们如何对其进行修改。提示:修改 sum.cpp 程序,计算 sum = 1 + 1/2 + 1/3 + 1/4 + … 1/n!让 n = 20
#include "mpi.h"
#include <cstdio>
#include <cmath>
#include <cstdlib>
#define ARRAY_SIZE 1000000
int main (int argc, char *argv[]) {
int myid, numprocs;
int namelen;
int* numbers = new int[ARRAY_SIZE];
char processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Get_processor_name(processor_name, &namelen);
printf("Process %d on %s\n", myid, processor_name);
for (int i=0; i<ARRAY_SIZE; i++)
numbers[i] = i; //could be randomly generated
int s = (int)floor(ARRAY_SIZE/numprocs);
int s0 = s + ARRAY_SIZE%numprocs;
int startIndex = s0 + (myid-1)*s;
int endIndex = startIndex + s;
double startwtime;
if (myid == 0) {
startwtime = MPI_Wtime();
}
int i;
int part_sum = 0;
if (myid == 0) {
// master worker - comput the master's numbers
for (i=0; i<s0; i++) {
part_sum += numbers[i];
}
printf("Process %d - startIndex 0 endIndex %d; part_sum %ld\n",
myid, s0-1, part_sum);
} else {
//slave's work
for (i= startIndex; i<endIndex; i++) {
part_sum += numbers[i];
}
printf ("Process %d - startIndex %d endIndex %d; part_sum %ld\n",
myid, startIndex, endIndex-1, part_sum);
}
int sum = 0;
MPI_Reduce(&part_sum, &sum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
if (myid == 0) {
double runTime = MPI_Wtime() - startwtime;
printf("Execution time (sec) = %f sum = %ld \n",
runTime, sum);
}
delete[] numbers;
MPI_Finalize();
}
解决方案
推荐阅读
- python - While 循环在允许 if 语句运行之前要求输入两次
- python-3.x - 为什么 Visual Studio 无法识别已安装的包?
- python - 如何打印 response.content 的特定部分
- xero-api - 如何使用 OAuth 2.0 在 Xero 中生成访问令牌?
- mysql - 使用spring数据jpa和mysql检查两个日期之间的日期
- javascript - 找一个空数组,修改json
- google-cloud-platform - Cloud SDK:gcloud sql 实例描述抛出错误 404:Cloud SQL 实例不存在
- laravel - 如何在多租户 SaaS 应用程序中为每个租户管理不同的队列?
- unit-testing - Resharper 测试窗口显示“已中止”,但所有测试均通过
- excel - 使用 VBA 对零售网站进行网页抓取