3

I want to ask a question about c++ i/o. If I use cin, cout with freopen(), is it necessary to put sync_with_stdio(false) or is there any way to speed it up? I noticed that using cout without sync_with_stdio(false) is a bit faster and it's no slower or faster than scanf().

Reading with sync_with_stdio(false) and cin takes around 3.7 seconds Reading without sync_with_stdio(false) takes around 6 seconds With scanf() takes 1.7 seconds

#include <bits/stdc++.h>
using namespace std;


int main() {
    ios_base::sync_with_stdio(false);
    freopen("i.inp", "r", stdin);
    freopen("o.out", "w", stdout);
    vector<int> a(10000000, 0);
    for (int i = 0; i < 10000000; i++) {
        cin >> a[i];
        //scanf("%d", &a[i]);
    }
    return 0;
}

Writing with sync_with_stdio(false) and cout takes 2.7 seconds and without sync_with_stdio(false) takes 2.5 seconds while printf being the fastest

#include <bits/stdc++.h>
using namespace std;


int main() {
    ios_base::sync_with_stdio(false);
    freopen("i.inp", "r", stdin);
    freopen("o.out", "w", stdout);
    for (int i = 0; i < 10000000; i++) {
        cout << 1 << " ";
        //printf("%d", 1);
    }
    return 0;
}

While reading, sync_with_stdio(false) actually helps but writing with it takes longer which makes me a little confused and wondering if I should use it or not or just stick with scanf and printf.

I used codeblock for execution time measurement.

  • 2
    `sync_with_stdio(false)` is not necessary, but might give better performance. If it don't, then don't use it. [Here](https://stackoverflow.com/a/9371717/6486738) is an interesting discussion about it. – Ted Klein Bergman Nov 30 '20 at 05:33
  • 1
    Please show a [mre], what is the input you are reading? What code are you using to read it? What performance are you getting? What performance do you require? Which platform are you running on? – Alan Birtles Nov 30 '20 at 08:12
  • Add some more info. With reading its a huge boost but with writing, its like it does the opposite – Dương Trần Nov 30 '20 at 10:48
  • 1
    is there a reason you're using `freopen` rather than just using `std::ifstream`/`std::ofstream`? Then `sync_with_stdio` wouldn't be an issue – Alan Birtles Nov 30 '20 at 18:41
  • I dont know if `fstream` gives any better performance. Might try it out. Thank you. – Dương Trần Dec 01 '20 at 04:58

0 Answers0