简体   繁体   English

用c ++编写数组到文本文件

[英]Writing arrays to text files in c++

I have to write some 5 to 6 large arrays of the same size to text files in C++. 我必须在C ++中用文本文件写一些相同大小的5到6个大型数组。 I am using only one "for loop" for writing all the arrays to text files. 我只使用一个“for循环”将所有数组写入文本文件。 The following is the code i'm using. 以下是我正在使用的代码。

ofstream kx_ecl("COARSE_PERMX.GRDECL");
ofstream ky_ecl("COARSE_PERMY.GRDECL");
ofstream kz_ecl("COARSE_PERMZ.GRDECL");
ofstream ntg_c("COARSE_NTG.GRDECL");
ofstream phi_c("COARSE_PORO.GRDECL");
ofstream multbv("MULTBRV.GRDECL");


kx_ecl<<"PERMX"<<endl;
ky_ecl<<"PERMY"<<endl;
kz_ecl<<"PERMZ"<<endl;
ntg_c<<"NTG"<<endl;
phi_c<<"PORO"<<endl;
multbv<<"MULTBRV"<<endl;

for (i=0;i<N;i++) {
    kx_ecl<<new_KX[i]<<endl;
    ky_ecl<<new_KY[i]<<endl;
    kz_ecl<<new_KZ[i]<<endl;
    ntg_c<<new_NTG[i]<<endl;
    phi_c<<new_por[i]<<endl;
    multbv<<MULTBRV[i]<<endl;
}

kx_ecl<<"/";
ky_ecl<<"/";
kz_ecl<<"/";
ntg_c<<"/";
phi_c<<"/";
multbv<<"/";
kx_ecl.close();
ky_ecl.close();
kz_ecl.close();
ntg_c.close();
phi_c.close();
multbv.close();

My question here is that is it faster if I output each of them individually one by one in which case it would have many for loops or leave it as it is. 我的问题是,如果我逐个单独输出它们,它会更快,在这种情况下它将有许多for循环或保持原样。 Also, is there any way to write the arrays to a file without using a for loop? 另外,有没有办法在不使用for循环的情况下将数组写入文件? I am asking because the output to files is taking a lot of time compared to the actual calculation in my code. 我问,因为与我的代码中的实际计算相比,输出到文件需要花费很多时间。

Are you aware that std::endl is flushing your ofstreams constantly? 你是否意识到std :: endl正在不断刷新你的游戏? You could push out '\\n' characters instead and just flush once at the end for each stream. 你可以推出'\\ n'字符,然后在每个流的末尾刷新一次。

I/O might still end up being the biggest piece of your time spent, but you are working against the buffering and do not seem in this example at least to be gaining anything from it. I / O可能仍然是你花费的时间中最重要的一部分,但是你正在反对缓冲,并且在这个例子中似乎不至少从中获得任何东西。 Going one array/file at a time might give you infinitesimally faster performance due to better memory locality (unless you're using so much memory you're swapping pages to disk), but the difference is probably getting completely lost in the huge cost of file writing. 一次运行一个数组/文件可能会因为更好的内存局部性而无法获得更快的性能(除非您使用如此多的内存将页面交换到磁盘),但差异可能会在巨大的成本中完全丢失。文件写作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM