简述

这里采用MPI_Reduce的集合通信的方式来计算

API

int MPI_Reduce(const void *sendbuf, void *recvbuf, int count,
               MPI_Datatype datatype, MPI_Op op, int root,
               MPI_Comm comm)

注意,在send和recv上,放的指针最好别指向同一个空间

#include <mpi.h>
#include <stdio.h>
#include <string>
#include <string.h>
#pragma warning(disable : 4996)
const int MAX_STRING = 100;

#define FUN(x) (x * x)

int main(int argc, char **argv) {
	int comm_sz;
	int my_rank;
	if (argc == 1) return 0;
	
	int n = strtol(argv[1], NULL, 10);
	double a = 0, b = 1;
	MPI_Init(NULL, NULL);
	MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
	MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

	int left = n % comm_sz;
	int localn = n / comm_sz + (my_rank < left);
	double h = (b - a) / n, locala, localb;

	if (my_rank < left) { locala = a + my_rank * localn * h; }
	else { locala = a + left * (localn + 1) * h + (my_rank - left) * localn * h; }
	localb = locala + localn * h;

	double x = locala; // initial x
	double localSum = ( FUN(locala) + FUN(localb)) / 2, totalSum=0;
	for (int i = 1; i < localn; ++i) {
		x += h;
		localSum += FUN(x);
	}
	localSum *= h;

	MPI_Reduce(&localSum, &totalSum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);

	if (my_rank == 0) printf("comm_sz: %d, n: %d, ans: %.5f\n", comm_sz, n, totalSum);
	
	MPI_Finalize();
}
  • 一样能算的正确,主要是会简化,同时用这样的方式也可以加速计算,毕竟求和的过程也被默认并行了。
PS D:\Code\C++\repo\MPITest\x64\Debug> mpiexec -n 3 ./MPITest.exe 1000
comm_sz: 3, n: 1000, ans: 0.33333
PS D:\Code\C++\repo\MPITest\x64\Debug>
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐