Is scanf faster than cin??

Jan 30, 2012 at 7:07am
I have read an article on solving SPOJ Problems. The author says that scanf() and printf() are three times faster than cin and cout. Is this true
Jan 30, 2012 at 7:29am
It is obviously implementation dependant. C++ does a bit of extra work - it performs code conversions where required (std::codecvt) and it provides robust handling of stream errors (by guarding them with sentries).

There is no technical reason why one should be noticeably slower than the other. You can execute a few million instructions in the time it takes the user to type in one character.

I am fairly certain that this particular author would have also raised another question - one that Stroustrup answers in his FAQ:

Why is the code generated for the "Hello world" program ten times larger for C++ than for C?

It isn't on my machine, and it shouldn't be on yours. I have even seen the C++ version of the "hello world" program smaller than the C version. In 2004, I tested using gcc -o2 on a Unix and the two versions (iostreams and stdio) yielded identical sizes. There is no language reason why the one version should be larger than the other. It is all an issue on how an implementor organizes the standard libraries (e.g. static linking vs. dynamic linking, locale support by default vs. locale support enabled through and option, etc.). If one version is significantly larger than the other, report the problem to the implementor of the larger.
- http://www2.research.att.com/~bs/bs_faq.html#Hello-world



Jan 30, 2012 at 7:56am
Thanks
Jan 30, 2012 at 8:17am
I have heard that cin and cout are also slowed down due to their being synced with stdio. You can turn that off using sync_with_stdio(false);
http://cplusplus.com/reference/iostream/ios_base/sync_with_stdio/
Jan 30, 2012 at 3:39pm
Why are you even asking that question? Is there any particular reason you would have to be concerned with the speed of cin or cout?
Topic archived. No new replies allowed.