arrays - MPI - 发送数组段

标签 arrays mpi send stride

所以我有一个 double 数组。我想发送,比如说每 5 个双倍,到接收过程。所以本质上,我需要一种发送特定 double 的方法,它们之间有大跨度。除了将 double 存储到发送缓冲区之外,是否有执行此操作的功能?制作我自己的派生类型会更好吗?

最佳答案

您绝对应该创建一个 MPI 数据类型;它使 MPI 库有机会避免从数组中进行编码的额外副本,并且在这种情况下使用 MPI_Type_vector() 非常简单。 :

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>

int main(int argc, char** argv)
{
    int size, rank;
    const int bigsize=50;
    const int stride = 5;
    const int count = (bigsize + stride - 1)/stride;

    const int sender = 0;
    const int receiver = 1;
    const int mytag = 1;

    MPI_Init(&argc,&argv);
    MPI_Comm_size(MPI_COMM_WORLD,&size);
    MPI_Comm_rank(MPI_COMM_WORLD,&rank);

    if (size < 2) {
        fprintf(stderr,"%s: Require at least two processors.\n", argv[0]);
        MPI_Finalize();
        exit(-1);
    }


    if(rank == sender)
    {
        double bigarray[bigsize];
        for (int i=0; i<bigsize; i++)
            bigarray[i] = 0.;

        for (int i=0; i<bigsize; i+=stride)
            bigarray[i] = i/stride;

        printf("[%d]: ", rank);
        for (int i=0; i<bigsize; i++)
            printf("%lf ", bigarray[i]);
        printf("\n");

        MPI_Datatype everyfifth;

        MPI_Type_vector( count, 1, stride, MPI_DOUBLE, &everyfifth);
        MPI_Type_commit(&everyfifth);

        MPI_Send(bigarray, 1, everyfifth, receiver, mytag, MPI_COMM_WORLD);

        MPI_Type_free(&everyfifth);
    }
    else if( rank == receiver )
    {
        double littlearray[count];

        MPI_Status status;

        MPI_Recv(littlearray, count, MPI_DOUBLE, sender, mytag,
                    MPI_COMM_WORLD, &status);

        printf("[%d]: ", rank);
        for (int i=0; i<count; i++)
            printf("%lf ", littlearray[i]);
        printf("\n");
    }

    MPI_Finalize();

    return 0;
}

编译和运行给出
$ mpicc -o vector vector.c -std=c99
$ mpirun -np 2 ./vector
[0]: 0.000000 0.000000 0.000000 0.000000 0.000000 1.000000 0.000000 0.000000 0.000000 0.000000 2.000000 0.000000 0.000000 0.000000 0.000000 3.000000 0.000000 0.000000 0.000000 0.000000 4.000000 0.000000 0.000000 0.000000 0.000000 5.000000 0.000000 0.000000 0.000000 0.000000 6.000000 0.000000 0.000000 0.000000 0.000000 7.000000 0.000000 0.000000 0.000000 0.000000 8.000000 0.000000 0.000000 0.000000 0.000000 9.000000 0.000000 0.000000 0.000000 0.000000 
[1]: 0.000000 1.000000 2.000000 3.000000 4.000000 5.000000 6.000000 7.000000 8.000000 9.000000 

关于arrays - MPI - 发送数组段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15483360/

相关文章:

mpi - Boost.MPI问题

python - 设置分布式 ipython/ipyparallel MPI 集群

cuda - 什么会导致 nvprof 不返回数据?

file - SFTP 使用 bash 脚本发送文件

C# 通过 HTTP 发送图像

安卓开发 |推文一个字符串

Jquery - 使用索引将多个值推送到数组中

python - Numpy 数组改变内部元素的值

javascript - 检查稀疏数组是否为空

c++ - std::array 和 std::vector 有什么区别?你什么时候使用一个而不是另一个?