views:

672

answers:

10

After performing some tests I noticed that printf is much faster than cout. I know that it's implementation dependent, but on my Linux box printf is 8x faster. So my idea is to mix the two printing methods: I want to use cout for simple prints, and I plan to use printf for producing huge outputs (typically in a loop). I think it's safe to do as long as I don't forget to flush before switching to the other method:

cout << "Hello" << endl;
cout.flush();

for (int i=0; i<1000000; ++i) {
    printf("World!\n");
}
fflush(stdout);

cout << "last line" << endl;
cout << flush;

Is it OK like that?

Update: Thanks for all the precious feedbacks. Summary of the answers: if you want to avoid tricky solutions, just simply don't use endl with cout since it flushes the buffer implicitly. Use "\n" instead. It can be interesting if you produce large outputs.

+9  A: 

Sending std::endl to the stream appends a newline and flushes the stream. The subsequent invocation of cout.flush() is superfluous. If this was done when timing cout vs. printf then you were not comparing apples to apples.

William Bell
For the comparative test I used two separate functions without flushing and executed the prg. twice, calling one method and the other. In this example I just wanted to demonstrate the "mixing" of the two methods.
Jabba
I suspect the reason cout is slower is that it is flushing after every line. printf flushes only when a buffer fills up or you explicitly flush. Flushes are expensive because they energize the mechanical parts of the disk.
Mike Dunlavey
Would it be possible to switch off cout's autoflush on std::endl and thus make it similar to printf?
Jabba
To answer my previous comment: use `"\n"` instead of `endl` to avoid flush after each line. See also http://stackoverflow.com/questions/1924530/mixing-cout-and-printf-for-faster-output/1926432#1926432 .
Jabba
@Jabba: I bet a lot of people would like to know that.
Mike Dunlavey
A: 

Mixing C++ and C iomethods was recommended against by my C++ books, FYI. I'm pretty sure the C functions trample on the state expected/held by C++.

Paul Nathan
C++ is designed to play with C i/o methods - remember, you are talking about a single runtime here.
anon
I dimly remember mixing C and C++ I/O under older versions of GCC incurred a performance hit. For all I know, it still could, but I haven't seen this mentioned recenly. Perhaps that's why the books were against it?
outis
I'm glad they play nice now. I remember strange things happening years ago, last time I tried (gcc 2.72 or somesuch; I remember having to explicitly instantiate my templates with #pragmas), and because of that I've avoided mixing them. Besides, where I work people are vehemently anti-iostreams. (I don't have a problem with them except for their excessive verbosity due to extreme overuse of operator overloading; I printed a lot of fixed-width 0-prefixed hex values and the formatters for those are insane.)
Mike D.
Neil: I don't recall why anymore; it's been literally years. outtis: perhaps.
Paul Nathan
I think it was GCC 2.95 that I was thinking of. GCC 3 might have fixed the performance hit.
outis
+1  A: 

You can use sync_with_stdio to make C++ IO faster.

cout.sync_with_stdio(false);

Should improve your output perfomance with cout.

Juan
Except then you do have to perform explicit flushes to mix the C++ and C style output funcytions, so you are not likely to gain much, if anything.
anon
This should remove the need for using both. Havent used it myself, but I heard a number of long speeches from classmates on how much faster cout is using this.
Juan
@Neil: When cout is synced with stdio, how often are flushes? I'd expect they would flush after every << operator, at least, since << doesn't know if the next operation is printf() and I'd be surprised if stdio has a dependency on (i.e. synchronizes with) iostreams.
Mike D.
@Juan: Just wondering, when we do `cout.sync_with_stdio(false);`, we are unsyncing the two streams. Isn't it the opposite of what we wanted to do?
Lazer
+8  A: 

By default, the C and C++ standard output streams are synchronised, so that writing to one causes a flush of the other, so explicit flushes are not needed.

anon
+4  A: 

You can further improve the performance of printf by increasing the buffer size for stdout:

setvbuf (stdout, NULL, _IOFBF, 32768);  // any value larger than 512 and also a
                  // a multiple of the system i/o buffer size is an improvement

The number of calls to the operating system to perform i/o is almost always the most expensive component and performance limiter.

Of course, if cout output is intermixed with stdout, the buffer flushes defeat the purpose an increased buffer size.

wallyk
+5  A: 

Also note that the C++ stream is synced to the C stream.
Thus it does extra work to stay in sync.

Another thing to note is to make sure you flush the streams an equal amount. If you continiously flush the stream on one system and not the other that will definately affect the speed of the tests.

Before assuming that one is faster than the other you should:

  • un-sync C++ I/O from C I/O (see sync_with_stdio() ).
  • Make sure the amount of flushes is comparable.
Martin York
I think you are conflating tie() with sync_with_stdio()
anon
Yep that was not correct. Re-worded to make it palatable.
Martin York
+1  A: 

You're performing I/O and you're worried about the cpu overhead of the function..? shrug

Andreas Bonini
I was worried about the execution speed.
Jabba
+2  A: 

Don't worry about the performance between printf and cout. If you want to gain performance, separate formatted output from non-formatted output.

puts("Hello World\n") is much faster than printf("%s", "Hellow World\n"). (Primarily due to the formatting overhead). Once you have isolated the formatted from plain text, you can do tricks like:

const char hello[] = "Hello World\n";
cout.write(hello, sizeof(hello) - sizeof('\0'));

To speed up formatted output, the trick is to perform all formatting to a string, then use block output with the string (or buffer):

const unsigned int MAX_BUFFER_SIZE = 256;
char buffer[MAX_BUFFER_SIZE];
sprintf(buffer, "%d times is a charm.\n", 5);
unsigned int text_length = strlen(buffer) - sizeof('\0');
fwrite(buffer, 1, text_length, stdout);

To further improve your program's performance, reduce the quantity of output. The less stuff you output, the faster your program will be. A side effect will be that your executable size will shrink too.

Thomas Matthews
The assertion that `puts` is *much faster* than `printf` is unfounded in most cases. In fact, `printf` performs almost as well as `puts` in most implementations I've investigated. It's never worse than 2:1 and more frequently somewhere around 1.3:1 or 1.2:1.
wallyk
+8  A: 
Jerry Coffin
Thank you for the thorough test. I always thought that `endl` was simply an alias to `"\n"`. As I can see, `endl` calls a flush too, while using `"\n"` will do buffering, just like printf.
Jabba
@Jerry Coffin: excellent answer! I never realized that avoiding `std::endl` could give such a speed-jump.
Lazer
A: 

Well, I can't think of any reason to actually use cout to be honest. It's completely insane to have a huge bulky template to do something so simple that will be in every file. Also, it's like it's designed to be as slow to type as possible and after the millionth time of typing <<<< and then typing the value in between and getting something lik >variableName>>> on accident I never want to do that again.

Not to mention if you include std namespace the world will eventually implode, and if you don't your typing burden becomes even more ridiculous.

However I don't like printf a lot either. For me, the solution is to create my own concrete class and then call whatever io stuff is necessary within that. Then you can have really simple io in any manner you want and with whatever implementation you want, whatever formatting you want, etc (generally you want floats to always be one way for example, not to format them 800 ways for no reason, so putting in formatting with every call is a joke).

So all I type is something like dout+"This is more sane than "+cPlusPlusMethod+" of "+debugIoType+". IMO at least"; dout++;

but you can have whatever you want. With lots of files it's surprising how much this improves compile time, too.

Also, there's nothing wrong with mixing C and C++, it should just be done jusdiciously and if you are using the things that cause the problems with using C in the first place it's safe to say the least of your worries is trouble from mixing C and C++.

Charles Eli Cheese