cout or printf which of the two has a faster execution speed C++?
Asked Answered
E

16

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?

Excepting answered 22/5, 2009 at 6:55 Comment(6)
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.Noncommittal
@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); }Volga
@Volga - 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.Noncommittal
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).Ushas
Possible duplicate of which is faster, and which is more flexible: printf or cout?Enamel
"I always wondered which has a faster execution speed printf or cout?" - There's no way to know without testing. Even the same way of producing output can have different speed on different implementations/Operating Systems/etc. Also what compiler you use and what compiler optimization level you use can have an effect. So, this question is not really answerable.Lenee
M
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...

Mop answered 22/5, 2009 at 7:0 Comment(6)
Neither a complex inheritance hierarchy nor passing objects around by itself induces overhead.Keating
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.Mop
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.Catamnesis
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.Mop
@Hexagon, how are inheritance and locality related?Keating
Dave - Inheritance typically (but not always) implies calling several small functions that may not be locally together in memory. This may have an extra cost - both because calling more functions, but also because more cache lines may be needed.Mop
C
22

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.

Catamnesis answered 22/5, 2009 at 7:3 Comment(9)
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.Mop
@Hexagon: If that is the case, you would most likely be logging to a file or using a custom logging system, in which case you're going to get very good performance anyway.Catamnesis
True, but your underlying logging system probably uses either the printf() approach or the iostream approach.Mop
@Hexagon: Yeah, most likely, though it likely uses a few tricks to squeeze performance out of either method, making the difference negligible.Catamnesis
When converting 128k vector data to text, the difference does matter a lot.Huppah
@peterchen: Overwhelming evidence says otherwise. :)Catamnesis
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.Aitken
On embedded systems, this does matter!Stubborn
To toss another thing on the pile of "when does it matter": competitive programming is one of the areas where I/O speed is important and often output needs to have specific formatting, so knowing which one is faster can be quite handy. Should they be equally fast, then it is a matter which is faster to code.Arteriovenous
A
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

Aeon answered 28/9, 2011 at 7:23 Comment(0)
P
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.

Pullen answered 22/5, 2009 at 7:8 Comment(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/consoleHokku
S
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.

Stage answered 22/5, 2009 at 7:8 Comment(0)
B
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.

Barnhill answered 17/6, 2011 at 15:49 Comment(0)
K
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.

Kreiner answered 22/5, 2009 at 7:41 Comment(0)
M
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.

Milliliter answered 22/5, 2009 at 7:43 Comment(0)
C
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.

Classicist answered 22/5, 2009 at 7:8 Comment(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 :)Excepting
M
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

Murrumbidgee answered 7/3, 2017 at 20:17 Comment(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.Roundhead
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 codeMurrumbidgee
please initialise your variables to zero. After that, three of them takes almost same timeLietuva
G
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://mcmap.net/q/271508/-why-is-istream-ostream-slow-duplicate):

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

Grazia answered 4/1 at 23:33 Comment(0)
J
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 ;)

Johannejohannes answered 22/5, 2009 at 7:22 Comment(0)
N
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.

Noncommittal answered 22/5, 2009 at 8:20 Comment(0)
S
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?

Synthiasyntonic answered 23/5, 2009 at 9:21 Comment(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.Murrumbidgee
@Murrumbidgee - Fair enough.But I think there are still better approaches than depending on the relative speed of stdio vs iostreams.Synthiasyntonic
H
-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.

Huppah answered 22/5, 2009 at 8:46 Comment(0)
H
-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.

Hesketh answered 22/5, 2009 at 7:43 Comment(1)
-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.Wisla

© 2022 - 2024 — McMap. All rights reserved.