Re: Which is faster?
On Jul 21, 7:20 am, Prasoon <prasoonthegr...@gmail.com> wrote:
Which is faster "cout" or "printf" ?
Which is tastier, apples or oranges?
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!
For this particular use, with the particular implementation you
were using.
But I think the statement "printf is faster than cout " is
nothing but dangerous over generalization.
Am I correct?
Yes. In particular, for the precise program you've written,
there's a good chance that actual IO is dominating both cases,
so the speed of the library code doesn't mean anything. In
fact, this will probably be the case for most uses of the
library.
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"
Which is ridiculous. Theoretically, cout can be slightly
faster, since it doesn't have to do any "parsing".
Theoretically, printf can be slightly faster, because there's
only one function call for complex formatting, as opposed to
many. Practically, it all depends, and if you find a large
difference, all it means is that one of them hasn't been
implemented very efficiently.
and got the output of the same program as
cout : 0.14
printf: 0.10
How did he get the output so fast ?
What was he outputting to? And what does clock() measure on
your system? (The presence of a getchar() at the end suggests
Windows, in which case, clock() is broken, and actually measures
elapsed time, rather than CPU.)
I think for 1000000 iterations my friend's output is
impossible! Tell me whether I got approximately correct output
or my friend?
If clock() works correctly, both of your figures are way too
large. On my Linux box, I get very close to 0 for both. (Your
output requires no formatting, so there is practically no CPU
involved in either case.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34