Re: Which is faster?
Prasoon <prasoonthegreat@gmail.com> kirjutas:
Which is faster "cout" or "printf" ?
I have written the following program
#include <iostream>
#include <cstdio>
#include <ctime>
int main()
{
std::clock_t start1, start2;
double diff1, diff2;
start1 = std::clock();
for ( long int i = 0; i < 1000000; ++i )
std::cout<<"*";
diff1 = ( std::clock() - start1 ) / (double)CLOCKS_PER_SEC;
start2 = std::clock();
for ( long int i = 0; i < 100000; ++i )
printf ( "*" );
diff2 = ( std::clock() - start2 ) / (double)CLOCKS_PER_SEC;
std::cout<<"\ncout: "<< diff1 <<'\n'<<"printf: "<< diff2 <<'\n';
getchar();
}
I got the output:
cout: 12.844
printf: 12.75
printf was slightly faster!
But I think the statement "printf is faster than cout " is nothing but
dangerous over generalization.
The actual console output probably dominates the timings anyway,
especially on Windows, so these numbers do not tell much.
Am I correct?
I am using Intel Core 2 duo processor E7400 @ 2.8 GHz and 4GB of RAM
A friend of mine said "printf is always faster than cout" and got the
output of the same program as
cout : 0.14
printf: 0.10
How did he get the output so fast ?
He probably did the right thing and redirected the output to a file or
/dev/null or NUL:.
I think for 1000000 iterations my friend's output is impossible! Tell
me whether I got approximately correct output or my friend?
You should worry about such things only when the program is too slow and
the profiling has shown that the output formatting is the culprit. Again,
when profiling one has to be careful and avoid measuring the console
output time, which may be huge, and which you don't have much control
over.
Also, don't forget that both printf and iostream are primarily text
formatting mechanisms, with extensive locale-dependent translations, etc.
When outputting large amounts of data one often has preformatted (binary
or not) data where formatted output does not make any sense.
OTOH, if you actually need formatted output, then you should use
iostreams, because you can imbue a specific locale to the single stream
object, whereas for printf one has to change the process-wide locale,
with all the drawbacks of having global data state. It's also much easier
to replace std::cout with a std::ostringstream than to replace printf()
with sprintf(), would you happen to need to format the data in memory
instead of immediate output.
hth
Paavo