lundi 20 juillet 2015

cout speed when synchronization is 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 ran both programs many times and this is the result (with g++ compiler):

cout: 17.116s

printf(): 9.153

So print() is two times faster than cout. I searched in stackoverflow for the reasons behind this behavior and I found that print() 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>

#include <ios>

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

cout with sync on: 17.116s

cout with sync off: 1.146s

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.

Aucun commentaire:

Enregistrer un commentaire