OpenMP与MPI混合编程小例子

下面的例子比较简单,主要为说明使用OpenMP以及MPI的混合编译命令。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include "mpi.h"
#include "omp.h"
#include <math.h>

#define N 1000000000

int main( int argc, char* argv[] ){
int rank, nproc;
int i,low,up;
double local = 0.0, pi, w, temp;

MPI_Status status;
MPI_Init( &argc, &argv );
MPI_Comm_size( MPI_COMM_WORLD, &nproc );
MPI_Comm_rank( MPI_COMM_WORLD, &rank );

w = 1.0/N;
low = rank*(N / nproc);
up = low + N/nproc - 1;

#pragma omp parallel for reduction(+:local) private(temp,i)
for (i=low;i<up; i++)
{
temp = (i+0.5)*w;
local = local + 4.0/(1.0+temp*temp);
}
MPI_Reduce(&local, &pi, 1, MPI_DOUBLE, MPI_SUM, 0,MPI_COMM_WORLD);
if(rank==0)
printf("pi = %.20f\n",pi*w);

MPI_Finalize();
}

编译命令如下:

1
2
mpicc -o my -fopenmp my.c -lm -O3
mpirun -np NUM_of_Procs -x OMP_NUM_THREADS=8 -machinefile nodes ./my

-------------End of the articleThank you for reading-------------
  • Author of this article:zfish
  • Link to this article: archives/7e40f356.html
  • Copyright Notice: All articles in this blog, except for special statements, please indicate the source!
0%