gpt4 book ai didi

c - 使用 MPI_Scatter 的并行搜索

转载 作者:太空宇宙 更新时间:2023-11-04 04:50:50 25 4
gpt4 key购买 nike

我是 mpi 编程的新手。我刚刚在 c 中使用 mpi_scatter 尝试了一个并行搜索程序。我想知道我的程序是否正确。但是当我执行一个没有 MPI_SCATTER 的程序时,即线性搜索,与并行程序相比,执行时间更短。为什么会这样?

#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 个进程运行此代码并且没有分散,则 b 的值将是未定义的。

您的代码似乎运行良好,生成进程和分散数据的通信的开销很可能相当于串行和并行之间的微小时间差异。尝试一个包含许多进程的超大数组 - 我预计这会比串行快得多。

关于c - 使用 MPI_Scatter 的并行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15609523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com