void t6(int argumentcount, char* argumentvector[]) {
int process_id, num_process;
int namelen;
char processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Init(&argumentcount, &argumentvector);
MPI_Comm_rank(MPI_COMM_WORLD, &process_id);
MPI_Comm_size(MPI_COMM_WORLD, &num_process);
MPI_Get_processor_name(processor_name, &namelen);
fprintf(stderr, "Hello world! Processor %d of %d on %s \n", process_id, num_process, processor_name);
MPI_Barrier(MPI_COMM_WORLD);
srand(time(NULL) + process_id * 10); // 初始化随机数发生器,srand() 用来设置 rand() 产生随机数时的随机数种子。参数 seed 必须是个整数,如果每次 seed 都设相同值,rand() 所产生的随机数值每次就会一样。
double *send_data1 = nullptr, send_data2;
double *recv_data1 = nullptr, *recv_data2 = nullptr;
int num_sendrecv = 3;
if (process_id == 0) {
send_data1 = new double[num_sendrecv * num_process];
std::cout << "send_data1" << std::endl;
for (int i = 0; i < num_sendrecv*num_process; ++i) {
send_data1[i] = ((double)rand() / (double)RAND_MAX)*100.0;
std::cout << send_data1[i] << std::endl;
}
}
recv_data1 = new double[num_sendrecv];
MPI_Scatter(send_data1, num_sendrecv, MPI_DOUBLE, recv_data1, num_sendrecv, MPI_DOUBLE, 0, MPI_COMM_WORLD);
std::string out_info = "process" + std::to_string(process_id) + "_recv_data1: ";
for (int i = 0; i < num_sendrecv; ++i) {
out_info += std::to_string(recv_data1[i]) + ", ";
}
std::cout << out_info << std::endl;
send_data2 = cal_avg(recv_data1, num_sendrecv);
std::cout << "process" + std::to_string(process_id) + "_avg: " + std::to_string(send_data2) << std::endl;
delete recv_data1;
delete send_data1;
if (process_id == 0) {
recv_data2 = new double[num_process];
}
MPI_Gather(&send_data2, 1, MPI_DOUBLE, recv_data2, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
if (process_id == 0) {
std::cout << "the following averages were calculated for each set of data" << std::endl;
for (int i = 0; i < num_process; ++i) {
std::cout << "process" << i << " " << recv_data2[i] << std::endl;
}
}
delete recv_data2;
MPI_Finalize();
}
c++ MPI_Scatter MPI_Gather计算平均数
于 2024-08-19 09:51:04 首次发布