Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cout speed when synchronization is off

Tags:

c++

c++11

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.

like image 703
Toni Joe Avatar asked Jul 20 '15 19:07

Toni Joe


1 Answers

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.

  1. You are mixing Cout with other stream output functions. Like, scanf/printf, gets/puts, getchar/putchar ... ) with C++-style IO (cin/cout ... )[1]

  2. 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

like image 170
Harlow44 Avatar answered Sep 18 '22 11:09

Harlow44