#include <mpi.h>
#include<vector>
#include<iostream>
void t13(int argumentcount, char* argumentvector[]) {
int procRank, procSize;
int namelen;
char processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Init(&argumentcount, &argumentvector);
MPI_Comm_rank(MPI_COMM_WORLD, &procRank);
MPI_Comm_size(MPI_COMM_WORLD, &procSize);
MPI_Get_processor_name(processor_name, &namelen);
MPI_Status status;
int nSamples = 100, numRP = 3;
int nPart = nSamples;
if (procSize >= 1)
nPart = nSamples / procSize + 1;
std::cout << "nPart=" << nPart << std::endl;
std::vector<std::vector<double>> report_params_values_all_procs(numRP);
for (size_t c = 0; c < report_params_values_all_procs.size(); ++c) {
report_params_values_all_procs[c].resize(nPart*procSize);
}
std::vector<std::vector<double>> report_params_values_one_proc(numRP);
for (size_t c = 0; c < report_params_values_one_proc.size(); ++c) {
report_params_values_one_proc[c].resize(nPart);
}
for (int s = 0; s < nPart; ++s) {
for (size_t c = 0; c < numRP; ++c) {
report_params_values_one_proc[c][s] = procRank + s + c*0.01;
}
}
for (size_t c = 0; c < numRP; ++c)
MPI_Gather(report_params_values_one_proc[c].data(),
report_params_values_one_proc[c].size()*sizeof(double),
MPI_BYTE,
report_params_values_all_procs[c].data(),
report_params_values_one_proc[c].size()*sizeof(double),
MPI_BYTE, 0, MPI_COMM_WORLD);
if (procRank == 0) {
for (int s = 0; s < nPart*procSize; ++s) {
std::cout << "id=" << s << ", ";
for (size_t c = 0; c < numRP; ++c) {
std::cout << report_params_values_all_procs[c][s] << ", ";
}
std::cout << std::endl;
}
}
}
MPI_Gather收集双重向量std::vector<std::vector<double>>,在这里是在内层数据收集的,把各个进程的内层向量收集到进程0
编译后在命令行执行mpiexec.exe -n 4 ./t13.exe ,这个指令开了4个进程