tags:

views:

911

answers:

12

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 constrains such as time limit for execution. My application has loads printing commands on the console. So which one would be preferable printf or cout?

Thanks in advance

+8  A: 

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

Hexagon
Neither a complex inheritance hierarchy nor passing objects around by itself induces overhead.
Dave Van den Eynde
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
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
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
+1 for doing a profile run with both versions.
lothar
@Hexagon, how are inheritance and locality related?
Dave Van den Eynde
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.
Hexagon
+10  A: 

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.

Noldorin
+1 for pointing out that it doesn't matter.
paxdiablo
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
@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.
Noldorin
True, but your underlying logging system probably uses either the printf() approach or the iostream approach.
Hexagon
@Hexagon: Yeah, most likely, though it likely uses a few tricks to squeeze performance out of either method, making the difference negligible.
Noldorin
Noldorin - So we are in agreement...
Hexagon
@Hexagon: Yeah, it seems we are now. :)
Noldorin
When converting 128k vector data to text, the difference does matter a lot.
peterchen
@peterchen: Overwhelming evidence says otherwise. :)
Noldorin
+4  A: 

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.

Daniel Earwicker
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: http://sourceforge.net/projects/console
Bluebird75
+1  A: 

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.

20th Century Boy
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
+2  A: 

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.

nhaa123
+1  A: 

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

Christoffer
+2  A: 

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.

Michael Burr
A: 

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.

ck
-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
+2  A: 

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.

sybreon
+2  A: 

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.

anon
A: 

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.

peterchen
A: 

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?

Michael J