From the following post:
Using scanf() in C++ programs is faster than using cin?
I know that after setting sync_with_stdio(false), cin can read faster. My question is: why?
Previously I thought that after calling sync_with_stdio(false), the system might create a buffer to decrease the stdin communication times: when a read request comes, the system might read several characters into a buffer before doing the parse. However, I realized this is not true since cin will block and wait for the customer to input characters one by one. So this means that no matter sync_with_stdio(false) is being called or not, the system has to wait the user’s input.
Then I thought that after calling sync_with_stdio(false), the stdin might change from blocked reading to unblocked reading. However, I tried to write the following code:
#include <fcntl.h>
int main()
{
auto saved_flags = fcntl(STDIN_FILENO, F_GETFL);
std::cout << saved_flags << std::endl;
std::ios_base::sync_with_stdio(false);
saved_flags = fcntl(STDIN_FILENO, F_GETFL);
std::cout << saved_flags << std::endl;
}
And the system output the same number, so this means that sync_with_stdio(false) does not change the flag of stdin at all.
From https://www.quora.com/Is-cin-cout-slower-than-scanf-printf/answer/Aditya-Vishwakarma the author mentioned:
Performance of cin/cout can be slow because they need to keep
themselves in sync with the underlying C library. This is essential if
both C IO and C++ IO is going to be used.
But it is too abstract to me. Can you tell me what is the real logic that causes the cin became faster after calling sync_with_stdio(false)?
Thanks