38

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?

6
  • 7
    If it is important to you, write a small app that does both and time it. That should take you all of 15 minutes to do.
    – anon
    May 22, 2009 at 7:46
  • 4
    @Neil: it's not that simple. std::cout and operator<< cause more code to be emitted at the point of calling. All printf logic is located in the CRT, but uses runtime logic to interpret the argument string. Thus, large programs with many call sites and many different formatting directives may see different effects than a small test program with just a big for(a lot) { printf("%d",i); }
    – MSalters
    May 22, 2009 at 8:29
  • @MSalters - not for something doing console I/O - the program will be I/O bound. And what you say is an argument for never testing anything.
    – anon
    May 22, 2009 at 8:38
  • i think it's fair to say that if anything, then printf is faster. (yes i measured, yes i switched off stdio synchronizing - all were slower than cout). May 23, 2009 at 11:42
  • Possible duplicate of which is faster, and which is more flexible: printf or cout?
    – phuclv
    Dec 30, 2017 at 13:23

16 Answers 16

32

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!

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

6
  • 3
    Neither a complex inheritance hierarchy nor passing objects around by itself induces overhead. May 22, 2009 at 7:06
  • 3
    A complex inheritance hierarchy usually means less locality, which is a performance impact. And passing objects around - well - passes objects around that wouldn't have been passed around otherwise... But I completely agree that these are anecdotal.
    – Hexagon
    May 22, 2009 at 7:23
  • 1
    There we have it. Your quick benchmark shows that the difference truly is negligible - the small advantage that cout had possibly could have been gained by other means, or something specific to the situation even.
    – Noldorin
    May 22, 2009 at 7:56
  • 2
    Noldorin - Completely so. No surprises here. It is likely that if I tweak the stuff being printed slightly (say, add leading zeroes or some other formatting, or add some extra strings in between the numbers), I could show the opposite results... but, enough is enough. There are better things to do in life.
    – Hexagon
    May 22, 2009 at 8:04
  • @Hexagon, how are inheritance and locality related? May 24, 2009 at 7:49
23

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.

9
  • 14
    I wouldn't go as far as saying that it doesn't matter. I can certainly imagine instances where it does (when you get to write millions of lines of log lines, for example). But they would be few and far between.
    – Hexagon
    May 22, 2009 at 7:21
  • 9
    When converting 128k vector data to text, the difference does matter a lot.
    – peterchen
    May 22, 2009 at 8:43
  • 2
    @peterchen: Overwhelming evidence says otherwise. :)
    – Noldorin
    May 22, 2009 at 11:03
  • 28
    I think it's really annoying when people ask a simple question like "Is X faster than Y?" and instead of getting answers to that question, "answerers" always tell them that it doesn't matter, or that it's a micro optimization and that kind of shit.
    – Tara
    Sep 28, 2013 at 18:50
  • 3
    On embedded systems, this does matter!
    – jaques-sam
    Nov 7, 2017 at 10:53
15

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

Try executing the following to deactivate this issue.

ios_base::sync_with_stdio(false)

http://www.cplusplus.com/reference/iostream/ios_base/sync_with_stdio/

http://msdn.microsoft.com/es-es/library/7yxhba01.aspx

6

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.

1
  • totally +1 on this. I had a test program spitting lots of log info on stdout. In regular console window on windows, it runs for 15 minutes. If I hide the window, it runs in 5 minutes. Same can also apply th Konsole on KDE if you are on Linux. I would suggest to reduce the amount of data printed of stdout/stderr, and use a log file instead for verbose information, keep the console to its minimum. Fortunately, this console program is very efficient: sourceforge.net/projects/console
    – Philippe F
    May 22, 2009 at 9:30
4

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.

4

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.

2

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.

2

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.

1

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.

1
  • I guess I agree with your point cout does a lot more than prinft. I asked this question out of curiosity and not to compare them.Thanks a lot :)
    – pirate
    May 22, 2009 at 7:12
1

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:

cpp.sh/94qoj

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

3
  • You raise a good point, some things are easily testable yourself, with just a few lines of code.**You should copy your code to this answer** in case your url does expire and others would want to use it.
    – Regular Jo
    Mar 8, 2017 at 3:42
  • 1
    my hypothesis is that endl takes a huge amount of time, because endl both prints a newline, and / or Carriage Return, depending on your OS. Then, it flushes the stream, consuming time. By the way, @RegularJoe, I will post the code
    – ndrewxie
    Mar 10, 2017 at 20:26
  • please initialise your variables to zero. After that, three of them takes almost same time
    – Mah35h
    Sep 22, 2020 at 2:34
1

It depends on multiple factors such as implementation, whether cout is synchronized with the underlying C stream and input but generally printf is faster. Here are some fundamental reasons why (from https://stackoverflow.com/a/65325727/471164):

  • Shared formatting state: every formatted output operation has to check all formatting state that might have been previously mutated by I/O manipulators. For this reason iostreams are inherently slower than printf-like APIs (especially with format string compilation like in Rust or {fmt} that avoid parsing overhead) where all formatting information is local.

  • Inefficient top-level API: formatting a message with iostreams normally consists of multiple formatting function calls because arguments and I/O manipulators are interleaved with parts of the message. For example, there are three such calls (godbolt) in

    std::cout << "The answer is " << answer << ".\n";
    

    compared to just one (godbolt) in the equivalent printf call:

    printf("The answer is %d.\n", answer);
    

    Each of these formatting function invocations has substantial overhead (see above). In replacement-based APIs like printf there is little overhead for literal portions of the string.

  • Extra buffering and synchronization. This can be disabled with sync_with_stdio(false) at the cost of poor interoperability with other I/O facilities.

That said printf is not particularly fast either and you might want to consider using C++23 std::print or the {fmt} library, it is based on.

0

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 ;)

0

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.

0

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?

2
  • "Nobody can read that fast". Well, unless you're writing to the terminal using a separate thread, cout and printf blocks the application. Not significant unless you're doing a lot of logging code, which OP might be doing.
    – ndrewxie
    Feb 19, 2019 at 14:38
  • @ndrewxie - Fair enough.But I think there are still better approaches than depending on the relative speed of stdio vs iostreams.
    – Michael J
    Feb 20, 2019 at 22:41
-2

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.

-6

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.

1
  • 11
    -1 for assuming that every application that writes to its output is designed to be ready in realtime by a user. Many server applications log to stdout even in performance-sensitive contexts.
    – Tom
    Dec 12, 2009 at 3:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.