scanf and printf are much faster than cin and cout

When I’m solving the Codeforces problem, 707D. Persistent Bookcase, I made some comparison for the performance of I/O function.

  • scanf() and printf()
  • cin >> and cout <<

 

Test

Let’s start from C++ common way, below code uses cin >> and cout <<

It took 748 ms.

Next, (old-school,) C way of implementation using scanf() and printf()

It took only 171 ms.

 

Result

function time
scanf() and printf() 171 ms
cin >> and cout << 748 ms

In this experiment, it appears that the speed of cin and cout is much much slower than scanf() and printf(), the difference is indeed quite huge.

The overhead of cin and cout took more than 500 ms! You might get a TLE using cin and cout while it is not necessary with scanf() and printf().

 

Conclusion: Use scanf and printf instead of cin and cout in programming contest!

Sponsored Links

Leave a Reply

Your email address will not be published.