Ding Zhiyu Week 3 Study Report: MPI Study
[TOC]
MPI Basics
A Basic MPI Program Framework
#include <mpi.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
// 初始化MPI环境
MPI_Init(&argc, &argv);
// 获取当前进程的排名
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
// 获取总进程数
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
// 让每个进程打印出它的排名和总的进程数
printf("Hello world from rank %d out of %d processors\n", world_rank, world_size);
// 清理MPI环境
MPI_Finalize();
return 0;
}
Timing Framework
#include <stdio.h>
#include <mpi.h>
int main(int argc, char *argv[])
{
MPI_Init(&argc, &argv);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
double start_time = MPI_Wtime();
// ... 在这里执行你的并行代码 ...
// ... 在这里执行你的并行代码 ...
double end_time = MPI_Wtime();
double elapsed_time = end_time - start_time;
// 在所有进程中找到最大的运行时间
double max_elapsed_time;
MPI_Reduce(&elapsed_time, &max_elapsed_time, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
// 在主进程中打印最大运行时间
if (rank == 0)
{
printf("\ntime:\n");
printf("Max elapsed time: %f seconds\n", max_elapsed_time);
}
MPI_Finalize();
return 0;
}
Compilation and Execution
To compile and run this MPI program, you need to have an MPI library installed and use an MPI-enabled compiler, such as mpicc. The compilation command would be something like:
mpicc -o mpi_hello_world mpi_hello_world.c
When running the MPI program, you need to use the mpirun or mpiexec command and specify the number of processes, for example:
mpirun -np 4 ./mpi_hello_world
This command will start 4 processes running your program. Each process will print its rank and the total number of processes, but the order of printing may be nondeterministic since they are running in parallel.
Point-to-Point Communication
MPI (Message Passing Interface) is a communication protocol used for programming inter-process communication between parallel computers running on different nodes. It is designed to work on distributed memory systems, which typically do not have a global address space. In such systems, communication between processes must be achieved through sending and receiving messages.