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?
source share