Re: Which is faster?
* Prasoon:
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.
Am I correct?
No. It is an overgeneralization but not a dangerous one. In practice, with
current C++ implementations and any I can imagine in the future (considering
that this state of affairs has persisted for about 10 years or so) printf will
be faster than cout. In theory cout *can* be faster, and I think it was Dietmar
Kuhl (modulo spelling) who once made a really really fast implementation --
Andrei Alexandrescu tried the same feat with some of the STL, called YASLI (Yet
Another Standard Library Implementation) but it was never completed except, as I
recall, an implementation of vector, and perhaps string but I'm not sure.
What you should be mainly be concerned about instead, is correctness and
maintainability.
Unfortunately for iostreams these concerns are in direct conflict. There is far
better type safety that for printf family, although still with UB for some input
operations. On the other hand, for any but the most trivial formatting and
parsing, the iostream code becomes really verbose & messy, downright ugly,
employing so complex functionality that whole tomes have been written about it.
But, for simple test & research & learning programs you can use a simple subset
of iostream functionality where the type safety outweights the verbosity. :-)
For those kinds of small programs there's no contest really: at least for the
novice iostreams are there the default choice, the only sane choice.
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 ?
Perhaps he directed the output to /dev/null (or nul in Windows)?
I think for 1000000 iterations my friend's output is impossible! Tell
me whether I got approximately correct output or my friend?
Probably both of you. <g>
Cheers & hth.,
- Alf