Question

I am currently writing a simulation in C++ (on OSX). The biggest time effort runs into storing the data, where the output is a table of double pairs t and f(t).

Until now I used the (simplified) code:

ofstream ofs;
ofs.open("test");
for(int i = 0; i < 4e7; i++){
    ofs << i;
}

ofs.close();

Since everthing is stored in 1's and 0's my guess was, that using the binary format would be more time efficient. But the follwing change (ios::binary) did not improve the computing time:

ofstream ofs;
ofs.open("test", ios::binary);
for(int i = 0; i < 4e7; i++){
    ofs << i;
}

ofs.close();

Was my guess wrong or do I need to add something?

Was it helpful?

Solution

No, not really. std::cout is linked to the console, and the speed of this is mostly OS dependent.

That being said, there are a few simple tricks to speed up console output:

  1. Create a stringstream buffer and output that in one << call. This has improved the speed at which my output landed in the Windows console a lot.
  2. Unsync the C++ streams from the C io library by using sync_with_stdio.
  3. If you don't need the output to be readable, you can write raw bytes and do away with any formatting of numbers, but this is a very specific case.

OTHER TIPS

ios::binary only enables or disables some OS-specific conversions from text to a binary representation and back. For example, Windows represents '\n' as a pair of bytes (13, 10) whereas in UNIX it is represented as a single byte (10). In your case, ios::binary makes no difference at all.

What you could to to improve performance is to use some low-level representation for you data, so that you don't have to convert integers or doubles into text representation and back. Storing plain data in arrays and writing them into files by large chunks would be the fastest way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top