【问题标题】:Parallel output using MPI IO to a single file使用 MPI IO 并行输出到单个文件
【发布时间】:2013-03-10 20:42:11
【问题描述】:

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

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

  1. 通过谷歌搜索,我了解到,将数据文件写成二进制文件(我在这个文件中只有十进制数字)而不是 *.txt" 文件要好得多。因为没有人会读这个文件,但仅限计算机。

  2. 我尝试自己实现(但使用格式化的输入/输出而不是二进制文件),但我得到了不正确的行为。

到目前为止我的代码如下:

#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 作为文本文件写入时做错了。

应该如何更改代码以便能够保存

  1. 作为.txt文件(格式输出)
  2. 作为 .dat 文件(二进制文件)

【问题讨论】:

    标签: io parallel-processing mpi output


    【解决方案1】:

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

    MPI_Offset offset = sizeof(double)*Pstart;
    

    不是

    MPI_Offset offset = sizeof(double)*rank;
    

    否则,您将让每个等级覆盖彼此的数据,因为(例如)nprocs=5 中的等级 3 开始在文件中的双数 3 处写入,而不是 (30/5)*3 = 18。

    另外,你希望每个等级都写NNN/nprocs doubles,而不是sizeof(double) doubles,这意味着你想要

    MPI_File_write(file, localArray, NNN/nprocs, MPI_DOUBLE, &status);
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 2011-09-15
      • 2012-11-13
      • 2015-03-13
      相关资源
      最近更新 更多