I've made some programs and saw that scanf and printf are considerably faster than using cin and cout?
-
1Does this answer your question? [cout or printf which of the two has a faster execution speed C++?](https://stackoverflow.com/questions/896654/cout-or-printf-which-of-the-two-has-a-faster-execution-speed-c) – dt170 May 17 '20 at 17:49
1 Answers
By default, cin/cout waste time synchronizing themselves with the C library’s stdio buffers, so that you can freely intermix calls to scanf/printf with operations on cin/cout.
Turn this off with
std::ios_base::sync_with_stdio(false);
Also many C++ tutorials tell you to write cout << endl
instead of cout << '\n'
. But endl
is actually slower because it forces a flush, which is usually unnecessary. (You’d need to flush if you were writing, say, an interactive progress bar, but not when writing a million lines of data.) Write '\n'
instead of endl
.
Also as C++ is object-oriented , cin
and cout
are objects and hence the overall time is increased due to object binding.
So, a simple one liner, std::ios_base::sync_with_stdio(false);
could make cin/cout
faster than printf/scanf
.
Hope this helps you

- 417
- 2
- 12

- 2,726
- 3
- 18
- 38
-
In defense of `std::endl`: It can save your ♥♥♥ when your program crashes at the customer and you only have the logs available. The speed loss nowadays almost always isn't that big of a deal so I would take that for the additional safety. Just understand the implications of both approaches. – Brotcrunsher May 17 '20 at 17:55
-
-
If cin/cout are slower because they are objects, how can it be faster than printf/scanf? Do those flush after every print / newline? – pacukluka May 17 '20 at 18:51