I wanted to compare the speeds of printf
and cout
in C++ using this code for cout
:
#include <iostream>
int main()
{
for (int i = 0; i < 150000; i++)
std::cout << "Hello!";
}
and this code for printf
:
#include <cstdio>
int main()
{
for (int i = 0; i < 150000; i++)
std::printf("Hello!");
}
I ran both programs many times and this is the result (with g++ compiler):
cout
: 17.116 s
printf
: 9.153 s
So printf
is two times faster than cout
. I searched in Stack Overflow for the reasons behind this behavior and I found that printf
is faster than cout
because its a function while cout
is an object. But I also learned that cout
is slower because it's synchronized with the standard C streams.
So what I did next is to turn off synchronization of all the iostream standard streams with their corresponding standard C streams with this code:
#include <iostream>
int main()
{
std::ios_base::sync_with_stdio(false);
for (int i = 0; i < 150000; ++i)
std::cout << "Hello!";
}
And surprisingly this is what I got:
printf
: 9.153 s
cout
with sync on: 17.116 s
cout
with sync off: 1.146 s
WOW! It's a huge difference!
So my question is: would it be a good practice to always turn off the synchronization?
Thanks in advance.
It Depends on if you're expected output has to be in order or not. And if you're mixing C-style or other output using the output stream. You do not want to ALWAYS turn off synchronization.
You DO NOT want to turn it off when.
You are mixing Cout with other stream output functions. Like, scanf/printf, gets/puts, getchar/putchar ... ) with C++-style IO (cin/cout ... )[1]
You are using threads with output that you want good output. "Concurrently accessing synchronized streams (i.e., streams for which this function returns true) never introduces data races: characters are read/written individually, although with no further guarantees on its order between threads. This may result in interleaved characters between threads unless proper synchronization of entire operations is enforced by the program."[1]
Other wise it is generally fine to Turn Off the synchronization.
also see: http://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With