hpc-lab-code/lab3/prime/analyze_load_balance.cpp
2026-01-21 18:02:30 +08:00

75 lines
2.5 KiB
C++

#include <cstdio>
#include <mpi.h>
// 分析负载均衡的辅助程序
int main(int argc, char *argv[]) {
int id, p;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &p);
MPI_Comm_rank(MPI_COMM_WORLD, &id);
int n = 100000;
if (argc == 2) {
n = atoi(argv[1]);
}
// 计算每个进程的工作量
int workload = 0;
for (int i = 2 + id; i <= n; i += p) {
workload++;
}
// 收集所有进程的工作量
int *workloads = nullptr;
if (id == 0) {
workloads = new int[p];
}
MPI_Gather(&workload, 1, MPI_INT, workloads, 1, MPI_INT, 0, MPI_COMM_WORLD);
if (id == 0) {
printf("\n=== 负载均衡分析 (N=%d, P=%d) ===\n", n, p);
printf("进程号\t检查的数字数量\t分配的数字范围\n");
printf("------------------------------------------------\n");
int total = 0;
for (int i = 0; i < p; i++) {
int start = 2 + i;
int end = n;
int count = workloads[i];
total += count;
printf("%d\t%d\t\t", i, count);
if (count <= 5) {
printf("[");
for (int j = 0; j < count && j < 3; j++) {
printf("%d", start + j * p);
if (j < count - 1 && j < 2) printf(", ");
}
if (count > 3) printf(", ...");
printf("]\n");
} else {
int last = start + (count - 1) * p;
printf("[%d, %d, ..., %d] (步长=%d)\n", start, start + p, last, p);
}
}
printf("------------------------------------------------\n");
printf("平均工作量: %d\n", total / p);
printf("最大工作量: %d\n", workloads[0]);
printf("最小工作量: %d\n", workloads[p-1]);
printf("负载不均衡度: %.2f%%\n",
100.0 * (workloads[0] - workloads[p-1]) / (double)workloads[0]);
printf("\n");
// 分析素数检测的计算成本
printf("=== 计算成本分析 ===\n");
printf("注意:小数字的素数检测快,大数字的素数检测慢!\n");
printf("进程0检测的数字: 2, %d, %d, ... (小数字,检测快)\n", 2+p, 2+2*p);
printf("进程%d检测的数字: %d, %d, %d, ... (大数字,检测慢)\n",
p-1, 2+(p-1), 2+2*(p-1), 2+3*(p-1));
printf("\n");
delete[] workloads;
}
MPI_Finalize();
return 0;
}