Slowdown in twice with ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); in C++

Revision en2, by dmkz, 2021-11-07 13:27:42

Hello! I want to show you the real life example where using of next features:

ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);

leads to slowdown of the program, written in C++, in two times.

Example is quite simple — just print binary representation of all numbers in range $$$[0,10^7)$$$:

#include <bits/stdc++.h>
using namespace std;
int main() {
    //ios::sync_with_stdio(false);
    //cin.tie(0); cout.tie(0);
    char buf[33]={0};
    buf[32] = '\n';
    for (int i = 0; i < 10'000'000; i++) {
        for (int bit = 30; bit >= 0; bit--) {
            buf[30-bit] = ((i >> bit) & 1) ? '1' : '0';
        }
        cout << buf;
    }
}

UPD. When I replaced buf[32] = '\n'; by buf[31] = '\n';, the situation wasn't changed.

If we run this example in codeforces custom invocation, then we will see Used: 1840 ms, 1184 KB. When we will uncomment speedup of C++ input/output, then we will see Used: 3759 ms, 1188 KB. It's a trap!

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
ru3 Russian dmkz 2021-11-07 13:37:34 273
en3 English dmkz 2021-11-07 13:35:20 221
en2 English dmkz 2021-11-07 13:27:42 99
ru2 Russian dmkz 2021-11-07 13:26:14 173 Мелкая правка: 'м - `'\n'` ситуация ' -> 'м - `'\n'`, ситуация '
ru1 Russian dmkz 2021-11-07 13:14:48 1267 Первая редакция перевода на Русский
en1 English dmkz 2021-11-07 13:10:19 1186 Initial revision (published)