gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
#include <mpi.h> #include <cstdlib> #include <cstdio> #include <ctime> #define N…
- User
#include <mpi.h> #include #include #include #define N 1000000000 int in_circle(double x, double y) { if (x*x + y * y <= 1) return 1; else return 0; } int main(int argc, char *argv[]) { int rank, size; int count = 0, global_count = 0; double pi; double start_time, end_time, time_taken; double mpi_speedup, serial_time;
srand(time(NULL)); MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); double x, y; start_time = MPI_Wtime(); for (int i = rank; i < N; i += size) { x = (double)rand() / RAND_MAX; y = (double)rand() / RAND_MAX; count += in_circle(x, y); } MPI_Reduce(&count, &global_count, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); if (rank == 0) { pi = (double)global_count / N * 4; end_time = MPI_Wtime(); time_taken = end_time - start_time; serial_time = time_taken * size; printf("MPI: # of trials = %14d, estimate of pi is %1.16f \nMPI wall time = %f seconds\n", N, pi, time_taken); printf("Serial wall time = %f seconds\n", serial_time); mpi_speedup = serial_time / time_taken; printf("speedup = %f\n", mpi_speedup); } MPI_Finalize(); return 0;}加上注释
- Assistant
#include <mpi.h> #include #include #include
#define N 1000000000 // 被投掷的点数
int in_circle(double x, double y) { // 判断点是否在圆内 if (x*x + y * y <= 1) return 1; else return 0; }
int main(int argc, char *argv[]) { int rank, size; int count = 0, global_count = 0; // 记录本进程内圆内的点数和全局圆内点数 double pi; double start_time, end_time, time_taken; // 记录时间 double mpi_speedup, serial_time; // MPI加速比和串行时间
srand(time(NULL)); // 播种随机数生成器 MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); // 获取进程数和自己的进程编号 double x, y; start_time = MPI_Wtime(); // 获取并记录开始时间 for (int i = rank; i < N; i += size) { // 每个进程投掷 N/size 个点,总共投掷 N 个点 x = (double)rand() / RAND_MAX; // 生成x坐标 y = (double)rand() / RAND_MAX; // 生成y坐标 count += in_circle(x, y); // 判断是否在圆内,更新本进程的圆内点数 } MPI_Reduce(&count, &global_count, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); // 将每个进程的圆内点数加总,存入进程0的global_count中 if (rank == 0) { // 只有进程0输出结果和加速比 pi = (double)global_count / N * 4; // 用公式计算pi end_time = MPI_Wtime(); // 获取并记录结束时间 time_taken = end_time - start_time; // 计算运行时间 serial_time = time_taken * size; // 串行时间等于运行时间乘以进程数 printf("MPI: # of trials = %14d, estimate of pi is %1.16f \nMPI wall time = %f seconds\n", N, pi, time_taken); printf("Serial wall time = %f seconds\n", serial_time); mpi_speedup = serial_time / time_taken; // 计算MPI加速比 printf("speedup = %f\n", mpi_speedup); } MPI_Finalize(); return 0;}