2013-03-21 29 views
4

我有一個非常簡單的任務要做,但不知何故我仍然卡住。使用MPI IO並行輸出到單個文件

我有一個BIG數據文件(「File_initial.dat」),應該由羣集上的所有節點(使用MPI)讀取,每個節點將對該BIG文件(File_size/number_of_nodes)的一部分執行一些操作。最後每個節點將其結果寫入一個共享的BIG文件(「File_final.dat」)。文件的元素數量保持不變。

  1. 谷歌搜索我的理解,這是更好的將數據寫入文件作爲二進制文件(我在這個文件只十進制數),而不是作爲* .TXT」文件。由於沒有人會讀這。文件,但只有電腦

  2. 我試圖實現自己的(但輸入/輸出和NOT二進制文件中使用的格式),但我得到不正確的行爲

到目前爲止我的代碼如下:

#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; 
} 

我明白,我做錯了什麼,而嘗試寫作雙文本文件。

應該如何更改代碼,以便能夠節省

  1. 爲.txt文件(格式輸出)
  2. 爲.dat文件(二進制文件)

回答

4

您的二進制文件文件輸出幾乎是正確的;但是您對文件內偏移量的計算以及要寫入的數據量不正確。你希望你的偏移是

MPI_Offset offset = sizeof(double)*Pstart; 

MPI_Offset offset = sizeof(double)*rank; 

否則,你將有每個等級覆蓋其他數據(比如說)等級3出nprocs=5開始的文件在雙號3寫作,不(30/5)* 3 = 18

而且,你希望每個級別寫NNN/nprocs雙打,不sizeof(double)雙打,這意味着你要

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

如何寫成文本文件是一個更大的問題;你必須在內部將數據轉換爲字符串,然後輸出這些字符串,確保通過仔細格式確定每行需要多少字符。這在本網站的this answer中有描述。

相關問題