Search code examples
c++iobufferiostreamstdio

increase buffer for cout


Citing Does setbuf() affect cout?

I want to increase the buffer size to improve the performance of cout (it is usually redirected to disk)

Can I do:

std::cout.rdbuf()->pubsetbuf(some_buffer, buffer_size);

And also

ios::sync_with_stdio(false);

Does this make sense?

EDIT: Also I am using multiple threads, so I was hoping to reduce the need for synchronization.


Solution

  • I would first check on the number of flushes that will make any larger buffer size irrelevant.

    Especially look, if you have a lot of cout << endl in your code and try replacing them by cout << '\n' instead, if you do not need the flushing effect of endl.

    As a last resort, before you try "optimizing" look for the root cause, e.g. try strace or similar tool to see the number of system calls actually occuring. (I hope this is helpful to your problem).

    Only, if that all is already looked after, a larger buffer size can actually help to reduce the number of system calls.

    Another slowing of cout output is, that it is often prepared to synchronize output with multiple threads, even when you only use one thread. This again can slow I/O heavily because of the overhead where a larger buffer is of no use.