Cin vs scanf, which is faster?

Asked

Viewed 1,284 times

7

In competitive programming it is common for several programmers to use scanf() and printf() in C++ code instead of using cin and cout.

And I’ve even seen problems that result in a Time Limit Exceeded (TLE - Time Limit Exceeded) when used cin and cout, but run within time when used scanf() and printf(), implementing the same idea in the algorithms.

Then there’s the doubt, scanf() is always faster than cin, will depend on the case or cin is faster?

1 answer

8


As performance may vary according to implementation, those who will do competitive programming will certainly test this on the implementation used to make sure which is best. If the person does not know that this is the right way it is better not to enter into competition.

In a good compiler (standard library), no bugs, well-written, if you use std::ios_base::sync_with_stdio(false) and not do anything crazy, in theory it is to be basically the same performance. It will hardly be the same, after all are different implementations.

Contrary to popular belief, you have a reasonable chance of streams C++ be up a little faster, at least in some scenarios (I’ve seen gains greater than 25% for the cin).

Anyway there are proposals to make a new way of formatting in C++ that greatly increases the performance in all scenarios.

  • 1

    I fully agree with you. I would even say that the implementation of a good compiler don’t need be overly concerned about equal performance, as the overall objective is not competition. So, maybe there are differences, but they are disregardable for almost all scenarios other than the competition. Even so, my intuition tells me that C++ streams tend to be slower due to OO implementation indirect. Don’t you think? If you have any indication otherwise, I think it would be nice to share it in the answer. :)

  • 1

    I also thought, until I saw some tests :) I’ll see if I find any. I think it may be that the overhead of Parsing formatting may be the cause, but I’m guessing.

  • 1

    True, it may be.

  • 1

    Cin good, scanf bad (not in terms of time, but in terms of usability)

  • @Joséx. also.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.