Tutorial :cout or printf which of the two has a faster execution speed C++?


I have been coding in C++ for a long time. I always wondered which has a faster execution speed printf or cout?

Situation: I am designing an application in C++ and I have certain constraints such as time limit for execution. My application has loads printing commands on the console. So which one would be preferable printf or cout?


Do you really need to care which has a faster execution speed? They are both used simply for printing text to the console/stdout, which typically isn't a task that demands ultra-high effiency. For that matter, I wouldn't imagine there to be a large difference in speed anyway (though one might expect printf to be marginally quicker because it lacks the minor complications of object-orientedness). Yet given that we're dealing with I/O operations here, even a minor difference would probably be swamped by the I/O overhead. Certainly, if you compared the equivalent methods for writing to files, that would be the case.

printf is simply the standard way to output text to stdout in C.
'cout' piping is simply the standard way to output text to stdout in C++.

Saying all this, there is a thread on the comp.lang.cc group discussing the same issue. Consensus does however seem to be that you should choose one over the other for reasons other than performance.


Each has its own overheads. Depending on what you print, either may be faster.

Here are two points that come to mind -

printf() has to parse the "format" string and act upon it, which adds a cost.
cout has a more complex inheritance hierarchy and passes around objects.

In practice, the difference shouldn't matter for all but the weirdest cases. If you think it really matters - measure!

Oh, heck, I don't believe I'm doing this, but for the record, on my very specific test case, with my very specific machine and its very specific load, 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.

(averaged over 10 runs).

The differences are so slim this probably means nothing...


On Windows at least, writing to the console is a huge bottleneck, so a "noisy" console mode program will be far slower than a silent one. So on that platform, slight differences in the library functions used to address the console will probably make no significant difference in practice.

On other platforms it may be different. Also it depends just how much console output you are doing, relative to other useful work.

Finally, it depends on your platform's implementation of the C and C++ I/O libraries.

So there is no general answer to this question.


The reason C++ cout is slow is the default sync with stdio.

Try executing the following to deactivate this issue.





Performance is a non-issue for comparison; can't think of anything where it actually counts (developing a console-program). However, there's a few points you should take into account:

  • Iostreams use operator chaining instead of va_args. This means that your program can't crash because you passed the wrong number of arguments. This can happen with printf.

  • Iostreams use operator overloading instead of va_args -- this means your program can't crash because you passed an int and it was expecting a string. This can happen with printf.

  • Iostreams don't have native support for format strings (which is the major root cause of #1 and #2). This is generally a good thing, but sometimes they're useful. The Boost format library brings this functionality to Iostreams for those who need it with defined behavior (throws an exception) rather than undefined behavior (as is the case with printf). This currently falls outside the standard.

  • Iostreams, unlike their printf equivilants, can handle variable length buffers directly themselves instead of you being forced to deal with hardcoded cruft.

Go for cout.


Another Stack Overflow question addressed the relative speed of C-style formatted I/O vs. C++ iostreams:

Note, however, that the benchmarks discussed were for formatting to memory buffers. I'd guess that if you're actually performing the I/O to a console or file that the relative speed differences would be much smaller due to the I/O taking more of the overall time.


In practical terms I have always found printf to be faster than cout. But then again, cout does a lot more for you in terms of type safety. Also remember printf is a simple function whereas cout is an object based on a complex streams hierarchy, so it's not really fair to compare execution times.


If you're using C++, you should use cout instead as printf belongs to the C family of functions. There are many improvements made for cout that you may benefit from. As for speed, it isn't an issue as console I/O is going to be slow anyway.


To settle this:

#include <iostream>  #include <cstdio>  #include <ctime>  using namespace std;    int main( int argc, char * argcv[] ) {      const char * const s1 = "some text";      const char * const s2 = "some more text";      int x = 1, y = 2, z = 3;      const int BIG = 2000;      time_t now = time(0);      for ( int i = 0; i < BIG; i++ ) {          if ( argc == 1 ) {              cout  << i << s1 << s2 << x << y << z << "\n";          }          else {              printf( "%d%s%s%d%d%d\n", i, s1, s2, x, y, z );          }      }      cout << (argc == 1 ? "cout " : "printf " ) << time(0) - now << endl;  }  

produces identical timings for cout and printf.


If you ever need to find out for performance reasons, something else is fundamentally wrong with your application - consider using some other logging facility or UI ;)


I recently was working on a C++ console application on windows that copied files using CopyFileEx and was echoing the 'to' and 'from' paths to the console for each copy and then displaying the average throughput at the end of the operation.

When I ran the console application using printf to echo out the strings I was getting 4mb/sec, when replacing the printf with std::cout the throughput dropped to 800kb/sec.

I was wondering why the std::cout call was so much more expensive and even went so far as to echo out the same string on each copy to get a better comparison on the calls. I did multiple runs to even out the comparison, but the 4x difference persisted.

Then I found this answer on stackoverflow..

Switching on buffering for stdout did the trick, now my throughput numbers for printf and std::cout are pretty much the same.

I have not dug any deeper into how printf and cout differ in console output buffering, but setting the output buffer before I begin writing to the console solved my problem.


Under the hood, they will both use the same code, so speed differences will not matter.

If you are running on Windows only, the non-standard cprintf() might be faster as it bypasses a lot of the streams stuff.

However it is an odd requirement. Nobody can read that fast. Why not write output to a file, then the user can browse the file at their leisure?


Why don't you do an experiment? On average for me, printing the string helloperson;\n using printf takes, on average, 2 clock ticks, while cout using endl takes a huge amount of time - 1248996720685 clock ticks. Using cout with "\n" as the newline takes only 41981 clock ticks. The short URL for my code is below:


link may have expired.

To answer your question, printf is faster.

#include <iostream>  #include <string>  #include <ctime>  #include <stdio.h>  using namespace std;  int main()  {    clock_t one;    clock_t two;    clock_t averagePrintf;    clock_t averageCout;    clock_t averagedumbHybrid;    for (int j = 0; j < 100; j++) {      one = clock();      for (int d = 0; d < 20; d++) {        printf("helloperson;");        printf("\n");      }      two = clock();      averagePrintf += two-one;        one = clock();      for (int d = 0; d < 20; d++) {        cout << "helloperson;";        cout << endl;      }      two = clock();      averageCout += two-one;        one = clock();      for (int d = 0; d < 20; d++) {        cout << "helloperson;";        cout << "\n";      }      two = clock();      averagedumbHybrid += two-one;    }    averagePrintf /= 100;    averageCout /= 100;    averagedumbHybrid /= 100;    cout << "printf took " << averagePrintf << endl;    cout << "cout took " << averageCout << endl;    cout << "hybrid took " << averagedumbHybrid << endl;  }  

Yes, I did use the word dumb. I first made it for myself, thinking that the results were crazy, so I searched it up, which ended up with me posting my code.

Hope it helps, Ndrewffght


Anecdotical evidence:
I've once designed a logging class to use ostream operators - the implementation was insanely slow (for huge amounts of data).

I didn't analyze that to much, so it might as well have been caused by not using ostreams correctly, or simply due to the amount of data logged to disk. (The class has been scrapped because of the performance problems and in practice printf / fmtmsg style was preferred.)

I agree with the other replies that in most cases, it doesn't matter. If output really is a problem, you should consider ways to avoid / delay it, as the actual display updates typically cost more than a correctly implemented string build. Thousands of lines scrolling by within milliseconds isn't very informative anyway.


You should never need to ask this question, as the user will only be able to read slower than both of them.

If you need fast execution, don't use either.

As others have mentioned, use some kind of logging if you need a record of the operations.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »