J Sherratt
J Sherratt

Reputation: 41

C++ Write to file line by line in loop or add to array and write to file after loop?

I have developed a CFD simulation model that runs largely within a single loop.

There is some data that needs outputting every time step such as convergence and iterations within the linear algebra solver.

What is the best practice to do this? Currently I have:

for(int tstep=0;tstep<maxTstep;++tstep)
{
    <code>
    outFile<<"data"<<endl;
{

Where a line is written to several files at the end of each loop. Is it better practice to do:

for(int tstep=0;tstep<maxTstep;++tstep)
{
    <code>
    outputVector.push_back("data");
}
for(int i=0;i<outputVector.size();++i) outFile<<outputVector[i]<<endl;

Whereby the output data is added to a vector and then written to a file all in one go?

Upvotes: 0

Views: 78

Answers (2)

Edy
Edy

Reputation: 470

If "data" is relatively small, then both method #1 & #2 would have very similar performance.

If "data" is large, e.g., several hundred bytes or above, then method #1 would be preferable as it avoids allocating and copying data into the outputVector (unless this is needed anyway).

Upvotes: 0

Vittorio Romeo
Vittorio Romeo

Reputation: 93384

The only correct answer is to measure and compare both approaches with your production build settings. Intuitively, I do not see why the vector approach would be any faster - I expect it to be slower.

Probably your current bottleneck is the use of std::endl, which forces any buffer to be flushed to its destination. Replace it with \n and only flush once at the end - this should give you a considerable speedup. E.g.

for(int tstep=0;tstep<maxTstep;++tstep)
{
    <code>
    outFile<<"data"<<'\n';
}

outFile.flush();

Upvotes: 2

Related Questions