Is cin / cout alternating slow?

To get started, I do std::ios_base::sync_with_stdio(false) . I have the following code snippets reading a million integers from a text file ( <input.txt >output.txt ):

 int tests; cin >> tests; for (int i = 0; i < tests; ++i) { int number; cin >> number; cout << number << "\n"; } 

and

 int tests; cin >> tests; vector<int> numbers(tests); for (int i = 0; i < tests; ++i) { cin >> numbers[i]; } for (int i = 0; i < tests; ++i) { cout << numbers[i] << "\n"; } 

Of course, they actually do more than just print the same numbers. The problem is that the first block takes about 4 times (6.2 seconds versus 1.8).

Rewriting the same code with printf / scanf takes 3 seconds in both cases. What is the reason for this?

+5
source share
1 answer

See std::basic_ios::tie , in particular these parts:

A linked stream is an output stream that synchronizes with a sequence controlled by the stream buffer ( rdbuf() ), i.e. flush() is called on the linked stream before any I / O on *this .

By default, the standard cin , cerr and clog streams are bound to cout . Similarly, their broad copies of wcin , wcerr and wclog tied to wcout .

You need to make sure that in a typical interactive program that does things like cout << "Enter something: "; cin >> something; cout << "Enter something: "; cin >> something; , a request appears on the screen before the program waits for input.

But in your case, these extra flush() calls defeat any stream buffering, which can lead to performance degradation.

You can break the tie with cin.tie(nullptr);

+3
source

Source: https://habr.com/ru/post/1208166/


All Articles