1. 程式人生 > >【MPI高效能運算】梯形面積積分計算

【MPI高效能運算】梯形面積積分計算

簡述

S = h [ f ( x

0 ) / 2 + f ( x 1
) + . . . + f ( x
n 1
) + f ( x n ) / 2 ] S = h * [f(x_0)/2 + f(x_1) + ... + f(x_{n-1}) + f(x_n)/2]

  • 將某個區間分為n段,每段長為h
  • 非常簡單的計算公式

MPI實現

#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;
	for (int i = 1; i < localn; ++i) {
		x += h;
		localSum += FUN(x);
	}
	localSum *= h;

	if (my_rank != 0) {
		// printf("locala: %f, localb: %f, localSum: %f, i:%d\n", locala, localb, localSum, my_rank);
		MPI_Send(&localSum, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
	}
	else {
		// printf("locala: %f, localb: %f localSum: %f\n", locala, localb, localSum);
		double tempSum = 0;
		for (int i = 1; i < comm_sz; ++i) {
			
			MPI_Recv(&tempSum, 1, MPI_DOUBLE, i, 0, MPI_COMM_WORLD, MPI_STATUSES_IGNORE);
			localSum += tempSum;
		}
		printf("comm_sz: %d, n: %d, ans: %.5f", comm_sz, n, localSum);
	}
	MPI_Finalize();
}
  • 呼叫3個執行緒,分10w個區間算[0,1]區間上的x^2的積分
PS D:\Code\C++\repo\MPITest\x64\Debug> mpiexec -n 3 ./MPITest.exe 100000
comm_sz: 3, n: 100000, ans: 0.33333
PS D:\Code\C++\repo\MPITest\x64\Debug>

在這裡插入圖片描述