用openmp和mpi混合求解莱布尼兹计算pi 添加计时函数
时间: 2025-06-25 17:20:09 浏览: 11
为了用 OpenMP 和 MPI 混合模式求解莱布尼茨公式来近似 π 的值,同时添加计时功能以测量整体性能和效率,我们可以按以下方式实现:
首先我们需要引入时间函数 `MPI_Wtime()` ,它是一个高精度的定时器,非常适合于并行环境中记录时间段落差。
以下是完整的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
int main(int argc, char *argv[]) {
int my_rank; // Process rank
int num_procs; // Number of processes
double pi = 0.0;
long step_count = 1e8;
if (argc > 1) { // If a second argument is provided use it as number of steps.
step_count = atol(argv[1]);
}
const double step = 1. / (double)(step_count);
// Initialize the MPI environment
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&num_procs); /* Get # procs */
MPI_Comm_rank(MPI_COMM_WORLD,&my_rank); /* Get process ID */
// Start timing for this node and total time across all nodes will be calculated later
double start_time = MPI_Wtime();
#pragma omp parallel reduction(+:pi)
{
int thread_num = omp_get_thread_num();
int threads_total = omp_get_num_threads();
for(long i=my_rank*threads_total + thread_num;i<step_count;i += num_procs*threads_total){
double x = ((i+0.5)*step)-1.;
pi += 4./(1.+x*x);
}
}
double local_result=pi*step;
double global_sum=0;
// Gather results from each processor into root processor's variable 'global_sum'
MPI_Reduce(&local_result , &global_sum , 1 , MPI_DOUBLE , MPI_SUM , 0 , MPI_COMM_WORLD );
if(my_rank == 0 ){
printf("PI value with %ld steps is %.16lf\n",step_count,global_sum );
double end_time=MPI_Wtime ();
printf("Time taken by program : %.6lfs\n",(end_time-start_time ));
}
// Finalize MPI system resources cleanup before exiting application
MPI_Finalize();
return EXIT_SUCCESS;
}
```
### 解释关键部分
- **初始化**: 使用 `MPI_Init`, 获取进程数及当前排名(`rank`)。
- **计时开始** (`start_time`): 对每个处理器单独开启计时。
- **OpenMP 并行循环**: 利用了 `#pragma omp parallel reduction(:)` 实现累加操作。其中每条线程只负责一部分项相加的任务。
- **结果收集**(Reduce)**:** 最终所有局部计算出来的π估计值通过 `MPI_Reduce` 发送到主节点汇总得出总的结果。
- **结束计时&打印信息**: 主进程中再次调用 `MPI_Wtime()` 结束计时,并输出整个程序耗时以及估算出的圆周率 Pi 值。
阅读全文
相关推荐


















