1
votes

I am new to mpi programming. I just tried a parallel search program using mpi_scatter in c . I want to know if my program is correct. But when I execute a program without MPI_SCATTER ie linear search the time to execute is lesser when compared to that of the parallel program.why is that happening?

#include<stdio.h>
#include<time.h>
#include<mpi.h>
main(int argc,char *argv[])
{
clock_t tic = clock();
int rank,size,a[10]={1,2,3,4,5,6,7,8,9,10},b[10],search=6,flag=0;      
long int i;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
MPI_Scatter(&a,5,MPI_INT,&b,5,MPI_INT,0,MPI_COMM_WORLD);
if(rank==0)
{
for(i=0;i<5;i++)
    {
        if(b[i]==search)
        {
            printf("\nNumber found!\t\t%d\t\t%d",rank,i);
            flag=1;
        }
        printf("\n%d\t\t%d",b[i],rank);
    }
}
if(rank==1)
{
    for(i=0;i<5;i++)
    {
        if(b[i]==search)
        {
            printf("\nNumber found!\t\t%d\t\t%d",rank,i);
            flag=1;
        }
        printf("\n%d\t\t%d",b[i],rank);
    }
}
MPI_Finalize();
clock_t toc=clock();
printf("\n\nElapsed: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC);
}

OUTPUT:
[Aburva@localhost mpipgms]$ /usr/lib/openmpi/bin/mpicc my_pgm2.c -o my_pgm2
[Aburva@localhost mpipgms]$ /usr/lib/openmpi/bin/mpirun -np 2 my_pgm2

1       0
2       0
3       0
4       0

Number found!       1       0

6       1
7       1
8       1
9       1
5       0

Elapsed: 0.070000 seconds
10      1

Elapsed: 0.080000 seconds
1

1 Answers

0
votes

Is your serial code not shown? If you ran this code using 1 process and no scatter then the values for b would be undefined.

Your code seems to be working fine, the overhead in generating processes and communication in scattering the data could well amount to the small difference in time between serial and parallel. Try a huge size array with many processes - I would expect that would be significantly faster than serial.