I_love_Hoang_Yen's blog

By I_love_Hoang_Yen, 9 years ago, In English

Hi,

Today I tried to solve 286C - Main Sequence, which required to read & print 106 ints.

There are already many blog posts that compares performance of cin, cout (with ios::sync_with_stdio(false) of course) vs printf, scanf. And the test results shown that for ints, cin and cout are equally fast (and sometimes even faster) than scanf, printf. But my submissions do not agree:

Note: I used cout << endl; in my submissions, but it prints endl only twice, so that should not be a problem here.

As you can see, except from input/output, my code is exactly the same. Am I doing anything wrong here?

UPD: I found another problem that cin/cout failed:

  • My submission with cin/cout: 9919391
  • A previously accepted code that use cin/cout but now got TLE: 9919511. This problem has warning "Package for this problem was not updated...", but the code doesn't use anything fancy, and also the printf/scanf version passed system test in 436ms (time limit is 1000ms). So I'm guessing that it is indeed because of cin/cout.

So, most likely, ios::sync_with_stdio(false); does not work well with the GNU C++ 4.9.2 which is used in Codeforces.

  • Vote: I like it
  • +51
  • Vote: I do not like it

| Write comment?
»
9 years ago, # |
  Vote: I like it +2 Vote: I do not like it

Try using cin.tie(0).

  • »
    »
    9 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    there is cin.tie(0) in last submission

    • »
      »
      »
      9 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Oh, sorry, I didn't notice it.

  • »
    »
    9 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    On some submissions, I had cin.tie(0), but it did not help. Usually that only results in 100ms difference.

»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Maybe mingw was updated recently.

It makes sense to find one of posts about it and recheck same problem, they checked

»
9 years ago, # |
Rev. 2   Vote: I like it +13 Vote: I do not like it

Maybe that only happens on Codeforces, on my PC cin/cout are significantly faster.

  • »
    »
    9 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Also SPOJ, Differences are too big between cin/cout and scanf/printf in SPOJ.

»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

endl flushes the stream:

printf("%d\n",i) + fflush(0) 7.477s

cout<<i<<endl 8.696s

printf("%d\n",i) 0.515s

cout<<i<<"\n" 1.654s

  • »
    »
    9 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    there's just 2 endl's, anyway substitution them to "\n" doesn't help

»
9 years ago, # |
  Vote: I like it +8 Vote: I do not like it

BTW, It's seems that sync_with_stdio(false) doesn't affect cout (here, at CF) at all(I've tested your second submission with this line commented and got ~ same time.