Fakultas Ilmu Komputer UI

mpi_bcred.c 806 Bytes
Newer Older
Ardhi Putra Pratama's avatar
Ardhi Putra Pratama committed
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
33
34
#include "mpi.h"
#include <stdio.h>
#include <math.h>
#define DATASIZE 10

int main(int argc, char **argv) {
    int myid, numprocs;
    int i, x, low, high, myresult=0, result;

    int data[DATASIZE] = {1,2,3,4,5,6,7,8,9,10}

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD, &myid);

    MPI_Bcast(data, DATASIZE, MPI_INT, 0, MPI_COMM_WORLD);

    /* add portion of data */
    x = DATASIZE/numprocs;	/* must be an integer */
    low = myid * x;
    high = low + x;
    for(i=low; i<high; i++) {
        myresult += data[i];
    }
    printf("%d has %d\n", myresult, myid);

    MPI_Reduce(&myresult, &result, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);

    if(0 == myid) {
        printf("The sum is %d.\n", result);
    }

    MPI_Finalize();
}