Which one is fast?

Hello guys, yesterday I was solving the problem RAJAPRO and was trying out a new template.
But I noticed something unusual(at least to me :p). Both the submissions have same code except in the first one I used scanf for input while in second one I used cin.

Link 1
Link 2

The difference in execution time was too high and I was amazed cz I thought scanf takes less time for input as compared to cin!!
Can anyone provide a valid justification to this and tell which one is faster?
Thanks :slight_smile:

you are using cin in the first one as well


Its true that scanf() is faster than cin because cin wastes time synchronizing itself with the stdio buffer.But turning off synchronization of all the iostream standard streams with stdio will make cin faster than scanf().
Read this article for more details.

Now in your link1 you have used scanf and cout and in link2 you have used cin,cout and turned off synchronization which makes both cin and cout faster but in first case you have used cout without truning off the synchronization.

So I think both these factor makes your program 1 run slower than the second.

1 Like

Thanks :slight_smile:
So,in link1 if I use printf and scanf will the result still be the same??

You may find this post interesting.

1 Like

Oops maybe I didn’t have a template for input of 2 integers so I used cin xD. Thanks for pointing that out @skyhavoc!

Thank you @meooow :slight_smile:

scanf and printf are indeed faster compared to cin and cout. In fact, the difference is especially visible in codeforces round.

If you use normal cin and cout when input is of magnitude ~{10}^{6} there, you will get TLE in taking input itself! (Speaking for Time limit of 2 seconds). This has resulted in many people failing real/large test cases there.

Even in JAVA, if you use scanner class, its possible that you may time out because its slow in taking input. A solution of scanner class taking ~3 seconds in JAVA takes only 0.75 seconds using Buffered Reader, further reduced fif you use user defined template for Faster I/O.

As for why is that, it has been answered multiple times on stackoverflow, like here- https://stackoverflow.com/questions/1042110/using-scanf-in-c-programs-is-faster-than-using-cin

1 Like

This may help you.


I think cin,cout with turned off synchronization if a little faster than scanf and printf !

Thanks for the help :slight_smile:

Thank you :slight_smile:

Ohh ok… Thanks!

But in codeforces its seen that even cin/cout with synchronization off is slower than scanf printf. I once got tle even after turning off the synchronization , so its safe to use scanf/printf always.

1 Like