1

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!

Luis Cruz
  • 1,488
  • 3
  • 22
  • 50

2 Answers2

1

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.

Community
  • 1
  • 1
rustyx
  • 80,671
  • 25
  • 200
  • 267
0

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

smac89
  • 39,374
  • 15
  • 132
  • 179
  • I am kind of mixing them though. I am using read() which is from I think. I am using this in a thread though, and the C++ iostream on the main thread. Should I still use std::ios::sync_with_stdio(false);? – Luis Cruz Apr 28 '15 at 04:03
  • @LuisCruz, if you are doing that then you shouldn't use that suggestion. Alternatively, I will suggest doing all your IO in C rather than mixing the two. Or switch entirely to C++ IO because you can still do the same stuff in C++. See [read](http://www.cplusplus.com/reference/istream/istream/read/), then you can make use of the optimization I have shown – smac89 Apr 28 '15 at 04:06