gpt4 book ai didi

io - 使用 MPI IO 并行输出到单个文件

转载 作者:行者123 更新时间:2023-12-01 01:11:02 30 4
gpt4 key购买 nike

我有一个非常简单的任务要做,但不知何故我仍然被卡住了。

我有一个 BIG 数据文件(“File_initial.dat”),它应该被集群上的所有节点读取(使用 MPI),每个节点将对这个 BIG 文件的一部分(File_size/number_of_nodes)和最后每个节点执行一些操作将其结果写入一个共享的 BIG 文件(“File_final.dat”)。文件的元素数量保持不变。

  • 通过谷歌搜索我了解到,将数据文件写为二进制文件(我在这个文件中只有十进制数)而不是 *.txt"文件要好得多。因为没有人会读这个文件,只有计算机。
  • 我试图自己实现(但使用格式化的输入/输出而不是二进制文件),但我得到了不正确的行为。

  • 到目前为止,我的代码如下:
    #include <fstream>
    #define NNN 30

    int main(int argc, char **argv)
    {
    ifstream fin;

    // setting MPI environment

    int rank, nprocs;
    MPI_File file;
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    // reading the initial file

    fin.open("initial.txt");
    for (int i=0;i<NNN;i++)
    {
    fin >> res[i];
    cout << res[i] << endl; // to see, what I have in the file
    }
    fin.close();

    // starting position in the "res" array as a function of "rank" of process
    int Pstart = (NNN / nprocs) * rank ;
    // specifying Offset for writing to file
    MPI_Offset offset = sizeof(double)*rank;
    MPI_File file;
    MPI_Status status;

    // opening one shared file
    MPI_File_open(MPI_COMM_WORLD, "final.txt", MPI_MODE_CREATE|MPI_MODE_WRONLY,
    MPI_INFO_NULL, &file);

    // setting local for each node array

    double * localArray;
    localArray = new double [NNN/nprocs];

    // Performing some basic manipulation (squaring each element of array)
    for (int i=0;i<(NNN / nprocs);i++)
    {
    localArray[i] = res[Pstart+i]*res[Pstart+i];
    }

    // Writing the result of each local array to the shared final file:

    MPI_File_seek(file, offset, MPI_SEEK_SET);
    MPI_File_write(file, localArray, sizeof(double), MPI_DOUBLE, &status);
    MPI_File_close(&file);

    MPI_Finalize();

    return 0;
    }

    我明白,我在尝试将 double 作为文本文件编写时做错了什么。

    应该如何更改代码才能保存
  • 作为 .txt 文件(格式输出)
  • 作为 .dat 文件(二进制文件)
  • 最佳答案

    你的二进制文件输出几乎是正确的;但是您对文件中的偏移量和要写入的数据量的计算不正确。你希望你的偏移量是

    MPI_Offset offset = sizeof(double)*Pstart;

    不是
    MPI_Offset offset = sizeof(double)*rank;

    否则你会让每个排名覆盖彼此的数据(比如)排名第 3 的 nprocs=5从文件中的双数 3 开始写入,而不是 (30/5)*3 = 18。

    此外,您希望每个等级都写 NNN/nprocs double ,而不是 sizeof(double) double ,意思是你想要
    MPI_File_write(file, localArray, NNN/nprocs, MPI_DOUBLE, &status);

    如何写成文本文件是一个更大的问题;您必须在内部将数据转换为字符串,然后输出这些字符串,通过仔细格式化确保您知道每行需要多少个字符。这在 this answer 中有描述在这个网站上。

    关于io - 使用 MPI IO 并行输出到单个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15545828/

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