Hyado's blog

By Hyado, history, 4 years ago, In English

I got stuck in 102253L - Limited Permutation because of slow printf (´・_・`)

Does anyone know why printf is much slower than cout in C++17(64bit)?

I measured execution time in Custom Test

printf

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, a, n) for(ll i = a; i < n; ++i)
int main() {
  ll n = 10000000;
  rep(i, 0, n) printf("%d ", n);
}
  • 3587 ms(GNU C++17 9.2.0 (64bit,2msys))
  • 1996 ms(GNU C++17 7.3.0)

cout

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, a, n) for(ll i = a; i < n; ++i)

int main() {
  ll n = 10000000;
  rep(i, 0, n) cout << 1000000 << " ";
}
  • 1138 ms(GNU C++17 9.2.0 (64bit,2msys))
  • 1544 ms(GNU C++17 7.3.0)
  • Vote: I like it
  • +21
  • Vote: I do not like it

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

How cout and printf are written are pretty much implementation independent. If you are particularly bent on performance, you can write custom print functions with putchar or fwrite, which will definitely be faster.

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

printf:
0.52user 0.00system 0:00.53elapsed 99%CPU (0avgtext+0avgdata 3500maxresident)k 0inputs+0outputs (0major+124minor)pagefaults 0swaps

cout:
0.56user 0.00system 0:00.56elapsed 99%CPU (0avgtext+0avgdata 3340maxresident)k 0inputs+0outputs (0major+121minor)pagefaults 0swaps

»
4 years ago, # |
  Vote: I like it +39 Vote: I do not like it

You can include #include <stdio.h> before #include <bits/stdc++.h> and you will get the same speed as with the 32bit version.

  • »
    »
    4 years ago, # ^ |
      Vote: I like it +3 Vote: I do not like it

    Thank you for your replying. I'm surprised to know this. Do you know why does this happen?

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it +27 Vote: I do not like it

      With #include <stdio.h> you call the C printf, without it you call std::printf. Different implementations, different speed. I have no idea why and what is the difference between them.

      Why the 32 bit uses the C printf? I am not sure, but I remember I read somewhere that MikeMirzayanov changed this behaviour by default (to call the C printf instead of std::printf) in C++14 and maybe the same changes were transferred to C++17 32 bit (because the C++14 is also 32 bit on Codeforces).

      Anyway, the objective answer to your question is I do not know.

      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it +3 Vote: I do not like it

        I didn't know there are two printfs, thanks a lot!

    • »
      »
      »
      4 years ago, # ^ |
        Vote: I like it +19 Vote: I do not like it
      • »
        »
        »
        »
        4 years ago, # ^ |
          Vote: I like it +6 Vote: I do not like it

        This seems to be the reason, thanks!