用MPI进行分布式内存编程(1)
2024-09-06 04:01:04
《并行程序设计导论》第三章部分程序
程序3.1运行实例
#include<stdio.h>
#include<string.h>
#include<mpi.h> const int MAX_STRING=; int main()
{
char greet[MAX_STRING];
int comm_sz; //进程数
int my_rank; //进程号 MPI_Init(NULL,NULL); //初始化
MPI_Comm_size(MPI_COMM_WORLD,&comm_sz); //返回进程数
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank); //返回进程号 if(my_rank!=)
{
sprintf(greet,"Greeting from process %d of %d",my_rank,comm_sz);
MPI_Send(greet,strlen(greet)+,MPI_CHAR,,,MPI_COMM_WORLD); //通信,发送
}
else
{
printf("Greeting from process %d of %d",my_rank,comm_sz);
int q;
for( q=;q<comm_sz;q++)
{
MPI_Recv(greet,MAX_STRING,MPI_CHAR,q,,MPI_COMM_WORLD,MPI_STATUS_IGNORE);//通信,接收
printf("%s\n",greet);
}
}
MPI_Finalize(); //告知系统MPI已使用完毕
return ; }
在天河平台运行结果
自己虚拟机运行结果
3.2运行实例
#include<stdio.h>
#include<string.h>
#include<mpi.h> double f(double x)
{
return x*x+x*x*x+;
}
double Trap(double left_endpt,double right_endpt,int trap_count,double base_len)
{ double estimate,x;
int i;
estimate=(f(left_endpt)+f(right_endpt))/2.0; //梯形面积
for(i =;i<=trap_count-;++i)
{
x=left_endpt+i*base_len;
estimate+=f(x);
}
estimate=estimate*base_len;
return estimate;
} int main()
{
int my_rank,comm_sz,n=,local_n;
double a=0.0,b=3.0,h,local_a,local_b;
double local_int,total_int;
int source; MPI_Init(NULL,NULL); //初始化
MPI_Comm_size(MPI_COMM_WORLD,&comm_sz); //返回进程数
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank); //返回进程号 h=(b-a)/n;
local_n=n/comm_sz; local_a=a+my_rank*local_n*h;
local_b=local_a+local_n*h;
local_int=Trap(local_a,local_b,local_n,h); if(my_rank!=)
{
MPI_Send(&local_int,,MPI_DOUBLE,,,MPI_COMM_WORLD);
}
else
{
total_int=local_int;
for(source=;source<comm_sz;source++)
{
MPI_Recv(&local_int,,MPI_DOUBLE,source,,MPI_COMM_WORLD,MPI_STATUS_IGNORE); //接受其他节点信息
total_int+=local_int;
}
} if(my_rank==)
{
printf("With n=%d trapezoids,our estimated\n",n);
printf("of the intergral from %f to %f=%.15e\n",a,b,total_int);
} MPI_Finalize();
return ; }
天河运行结果
最新文章
- MVC还是MVVM?或许VMVC更适合WinForm客户端
- source /etc/profile报错-bash: id:command is not found
- C#高级编程笔记 Day 8, 2016年9月 28日 (数组)
- PHP注册审核做法
- linux下发布的执行文件崩溃的问题定位 心得一则
- poj2269 Friends
- tuning 02 Diagnostic and Tuning Tools
- 转:Android ViewPager多页面滑动切换以及动画效果
- class属性添加多个类
- css animation 动画的制作
- collectionView 和 tableView的嵌套使用
- 再起航,我的学习笔记之JavaScript设计模式03
- 特殊计数序列——第一类斯特林(stirling)数
- Json Web Token(JWT)
- 【转】解决ubuntu13.10下,无法双击运行脚本文件
- 网络基础&#160;图解Windows系统下单网卡设置双IP访问不同网段的方法
- (一)JQuery动态加载js的三种方法
- Java Web入门学习(一) STS与Tomcat配置
- 20169205实验一 Java开发环境的熟悉(Linux+IDEA)
- supervisord常见问题