Luis Cruz
Luis Cruz

Reputation: 1634

Improving performance of ofstream?

I am communicating with some parallel processes using FIFOs. I am reading the pipe with read(). And I am writing to the named pipe by doing this:

ofstream pipe(namepipe);

pipe << data << endl;
pipe.close();

I have been noticing that the performance is horrible though! It takes like 40ms sometimes. It's an extreme latency in my opinion. I read that the use of std::endl can affect performance. Should I avoid using endl?

Does using ofstream affect performance? Are there any other alternatives to this method?

Thank you!

Upvotes: 2

Views: 2820

Answers (2)

rustyx
rustyx

Reputation: 85286

When working with large files with fstream, make sure to use a stream buffer and don't use endl (endl flushes the output stream).

At least the MSVC implementation copies 1 char at a time to the filebuf when no buffer was set (see streambuf::xsputn()), which can make your application CPU-bound, which will result in lower I/O rates.

So, try adding this to your code before doing the writing:

const size_t bufsize = 256*1024;
char buf[bufsize];
mystream.rdbuf()->pubsetbuf(buf, bufsize);

NB: You can find a complete sample application here.

Upvotes: 2

smac89
smac89

Reputation: 43078

A cheap hack:

std::ios::sync_with_stdio(false);

Note Use this only if you are not going to be mixing c IO with c++

The reason std::endl might affect i/o performance is because it flushes the stream. So to avoid this, you should use '\n'

Avoiding having to open and close multiple streams will also help

Upvotes: 0

Related Questions