In some Online Judge if we use cout , we get TLE but if we use printf we get Accepted. What is the reason for this?
@rashedcs printf is definitely faster than cout because of internal syncing / flushing in iostream i/o which normally slows down their performance. However using iostream with sync_with_stdio(false) makes i/o operations comparable to scanf/printf. And if we’re not mixing cstdio and iostream, we can turn it off, and then iostream is fastest.
Printf is faster.
here is an interesting record
compiling in Release using MSVC -
Printing 150,000 "Hello, World!"s (without using endl) takes about -
90ms for printf(), 79ms for cout.
Printing 150,000 random doubles takes about -
3450ms for printf(), 3420ms for cout.
It depends on which operating system u are using, but actually it doesn’t make much difference.
printfis faster compared to
coutmostly unless you have turned off the sync in which case both are at par. The difference between their execution time is not big enough to cause worries if your algorithm is working properly. Therefore it isn’t much useful to switch from one to another, just because it’s slow.
It will make no difference mostly, but you could consider using
'\n' instead of std::endl.
@rashedcs if you want to make cin cout faster just add this line in your code without quotes:
I’ve made some programs and saw that scanf and printf are considerably faster than using cin and cout? Most of my programs clear the execution time limit, mostly 3 seconds or 5 seconds, on online compilers when using scanf/printf which exceeded the limit while using cin/cout. by jetnet aa
here are the times for the five runs:
!.std::cout test: 1.125 s ; printf test: 0.195 s
2.std::cout test: 1.154 s ; printf test: 0.230 s
3.std::cout test: 1.142 s ; printf test: 0.216 s
4.std::cout test: 1.322 s ; printf test: 0.221 s
5.std::cout test: 1.108 s ; printf test: 0.232 s
Of one of code
As you can see, using printf and then fflushing takes about 5 times less time than using std::cout.