I assigned a char buffer to cout in order to speed things up. And as expected it was extremely efficient, iterating all numbers from 0 up to short unsigned upper limit dropped from 11.5 secs to around 0.1 sec. But to my surprise printf() works better as well by assigning cout a buffer, performing the same task, the printf() timer dropped from 3.04 to 0.1 as well. To make sure it wasn't an isolate case I performed the test multiple times and on varying numbers, as well as testing with std::ios::sync_with_stdio(false) and without it and the result was the same, a major speed-up for both, in fact, they both had about the same running time. So the question is how exactly does cout's member functions rdbuf() and pubsetbuf() affect printf()? What's the connection between cout and printf except their function?
Here's the code I used to test them on Visual Studio 2013:
1) You are measuring wall clock. You are seriously affected by OS buffer and IO throughtput. You are unlikely to get any significant results from your measurements. Measure CPU time actually spent in your program.
I'd redirect stdout to /dev/null and use stderr to display the time.
Don't have such incredible difference, both are around 70 ms.
> Then again intermixing printf and iostreams in one program after turning off synchronisation is undefined.
¿isn't your last snip still doing that? ¿or does the flush solve the problem?
It compiles either one or another part depending on if PRINTF macro is defined. You have to compile and run program several times with different configurations.
Don't have such incredible difference, both are around 70 ms.
I actually expected that. I believe my resuts are because MinGW links dynamically with C runtime library (MSVCRT). All test I saw shows comparable perfomance with C++ and C I/O
Ah, you are right. I need to fix that too. Behavior of different calls is actually not undefined, but different buffers might lead to problems (in previous snippet results were buried in the middle of file, because of printf buffering).