increase buffer for cout

爷,独闯天下 提交于 2019-12-07 17:42:25

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/7202147/increase-buffer-for-cout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!