Cout when sync off

I wanted to compare printf () and cout speed 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++)
    printf("Hello!");
}

      

I have run both programs many times and this is the result (with g ++ compiler):

cout: 17.116s

printf (): 9.153

So print () is twice as fast as cout. I searched on stackoverflow for the reasons for this behavior and I found that print () is faster than cout because its function while cout is an object. But I also found out that cout is slower because it is in sync with standard C streams.

So what I did next was to disable the synchronization of all standard iostreams with the corresponding standard C streams with this code:

#include <iostream>

#include <ios>

int main(){
    std::ios_base::sync_with_stdio(false);
    for(int i=0; i<150000; i++)
    std::cout << "Hello!";
}

      

And suddenly this is what I got:

printf (): 9.153

cout with sync: 17.116s

cout with sync disabled: 1.146s

WOW! This is a huge difference!

So my question is, would it be good practice to always turn sync off?

Thanks in advance.

+3


source to share


1 answer


It depends on whether the expected result should be ok or not. And if you mix C style or other output using the output stream. You don't want to ALWAYS turn off sync.

You do NOT want to disable it when.

  • You are mixing Cout with other stream output functions. For example scanf / printf, gets / puts, getchar / putchar ...) with IO (cin / cout ...) [ 1 ]

  • You are using streams with the outputs you need for good output. "Concurrent access to synchronized streams (ie Streams for which this function returns true) never enters data races: characters are read / written individually, although without any additional guarantees on its order between threads. This can lead to interleaving characters between threads, as long as the correct synchronization of the entire operation is performed by the program. " [ 1 ]



Another way is usually to stop turning off sync.

also see http://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio

0


source







All Articles