4

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.

2
  • you could just try it and benchmark it to see if it makes sense. Its quite implementation specific if it does. Commented Aug 26, 2011 at 9:39
  • 1
    The std::cout buffer has already been designed to be optimal for your system. It is unlikely you will achieve better performance (but please try), even if you find an improvement this may not translate to other systems as each std lib will be tuned to that system (or more specifically file system). Commented Aug 26, 2011 at 12:21

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Replacing <<endl by <<'\n'` is very important.
Yes, I am using multiple threads, and I was hoping that this would reduce synchronization without having to manually add a queue.
@Didier Trosset, yes I don't use endl :P
After further testing, it does make a bit of difference for the multithreaded case. about 5%.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.