gpt4 book ai didi

c++ - MPI_Allreduce 加倍

转载 作者:行者123 更新时间:2023-11-28 02:18:45 27 4
gpt4 key购买 nike

我正在尝试为我正在处理的排序找到所有处理器的全局最小值和最大值。我正在尝试使用 MPI_Reduceall

int rank, nproc;
MPI_Comm_size(MPI_COMM_WORLD,&nproc);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);

vector< vector<double> > buckets(nproc);
double local_min = *std::min_element(values_to_sort.begin(), values_to_sort.end());
double local_max = *std::max_element(values_to_sort.begin(), values_to_sort.end());

int min = 0;
int max = 0;

double global_min;
double global_max;

MPI_Allreduce(&local_min, &global_min, 1, MPI_2DOUBLE_PRECISION, MPI_MINLOC, MPI_COMM_WORLD);
MPI_Allreduce(&local_max, &global_max, 1, MPI_2DOUBLE_PRECISION, MPI_MAXLOC, MPI_COMM_WORLD);

cout << "local_min " << local_min << " local_max " << local_max << endl;
cout << "global_min " << global_min << " global_max " << global_max << endl;

显示了我的代码,但每次都出现段错误。这是一个简单的函数,使用以下方法生成的随机 double 调用:

int min = 0;
int max = 100;

vector<double> values_to_sort;
vector<double> sorted_values;
for(int i=0; i< 1000; i++)
{
values_to_sort.push_back( ((double) rand()*(max-min)/(double)RAND_MAX-min) );
}

如果有人知道为什么这个段错误,请告诉我。我真的很想以一种快速简单的方式获得全局最大值和最小值。

最佳答案

你真的需要在这里使用MPI_MINLOCMPI_MAXLOC吗?因为您陈述问题的方式和使用解决方案的方式,MPI_MINMPI_MAX 就可以了:

double local_min = *std::min_element(values_to_sort.begin(), values_to_sort.end());
double local_max = *std::max_element(values_to_sort.begin(), values_to_sort.end());

double global_min;
double global_max;

MPI_Allreduce(&local_min, &global_min, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD);
MPI_Allreduce(&local_max, &global_max, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);

cout << "local_min " << local_min << " local_max " << local_max << endl;
cout << "global_min " << global_min << " global_max " << global_max << endl;

现在,如果您真的需要拥有全局最小值和全局最大值的进程的等级,那么您确实需要 MPI_MINLOCMPI_MAXLOC。但是,您应该像这样使用它:

struct double_int {
double val;
int rank;
} local_min, local_max, global_min, global_max;

local_min.val = *std::min_element(values_to_sort.begin(), values_to_sort.end());
local_max.val = *std::max_element(values_to_sort.begin(), values_to_sort.end());
local_min.rank = local_max.rank = rank;

MPI_Allreduce(&local_min, &global_min, 1, MPI_DOUBLE_INT, MPI_MINLOC, MPI_COMM_WORLD);
MPI_Allreduce(&local_max, &global_max, 1, MPI_DOUBLE_INT, MPI_MAXLOC, MPI_COMM_WORLD);

cout << "on process " << rank << " local_min " << local_min.val
<< " local_max " << local_max.val << endl;
cout << "global_min " << global_min.val << " owned by process " << global_min.rank << endl;
cout << "global_max " << global_max.val << " owned by process " << global_max.rank << endl;

关于c++ - MPI_Allreduce 加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33226232/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com