【发布时间】:2021-04-17 01:54:37
【问题描述】:
我正在尝试将数组中的元素并行相加。我有一个算法示例,我遵循该算法将数组中具有不同步幅的元素相加:
input = [3,10,1,22,8,28,4,53,4,4,0,4,0,0,0,57]
First Stride (Add every N/2^1 to N/2^1 + N/2^(1+1):
input = [ 3,10,1,22,8,28,4,53,4,4,0,57,0,0,0,57]
Second Stride (Add every N/2^2 to N/2^2 + +N/2^(2+1):
input = [3,10,1,22,8,50,4,53,4,57,0,57,0,57,0,57]
Third Stride (Add every N/2^3 to N/2^3 + N/2^(3+1):
input = [3,10,11,22,30,50,54,53,57,57,57,57,57,57,57,57]
我编写了代码以将添加工作平均分配给我的处理器。 (需要注意的是,我试图避免使用 MPI_Scan)
每个处理器都有一个临时值,表示更改后的数组值,MPI_Gather 将其返回到 root,然后 root 将更改整个输入数组,MPI_cast 每个处理器的输入在之前再次执行添加工作进入下一步。
但是,我的结果似乎没有按我的意愿工作。如果有人能告诉我我在代码中做错了什么,我将不胜感激。
这是我的代码:(更新)
int DownPhaseFunction(int* input, int size_per_process, int rank, int totalarray, int size, int* Temp0)
{
//rank is the id of processor
//size is the total number of processors
int temp =0;
int index = 0;
int index0 = 0;
//First Stride
if(rank == 0)
{
input[(totalarray)-(totalarray/2)+(totalarray/4)-1] += input[(totalarray)-(totalarray/2)-1];
}
MPI_Bcast(input,totalarray,MPI_INT,0,MPI_COMM_WORLD);
//Start with Second Stride to the end
for (int i=4 ; i<totalarray ; i*=2)
{
//if the number of elements to be changed is larger than total size of processors, do a few more strides
for(int j=0;j<=i;j+=(size*totalarray/i))
{
index = ( (rank+1)*totalarray/i) + j;
if (index != totalarray)
{
temp = input[(index+(totalarray/i)/2)-1] + input[index-1];
}
else
{
temp = input[index-1];
}
//Gather the changed elements back to root
MPI_Gather (&temp, size , MPI_INT, Temp0, size, MPI_INT,0,MPI_COMM_WORLD );
//Let root change the changed elements in the input array
if(rank == 0)
{
for(int r=0; r<size; r++)
{
index0 = ((r+1)*totalarray/i)+j;
if( (index0) != totalarray)
{
input[(index0+(totalarray/i)/2-1)] = Temp0[r];
}
}
}
//send it back to every processor to do the next stride
MPI_Bcast(input,totalarray,MPI_INT,0,MPI_COMM_WORLD);
}
}
return(*input);
}
【问题讨论】:
标签: c performance parallel-processing mpi hpc