Re: Which is faster?
Prasoon wrote:
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?
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 ?
I think for 1000000 iterations my friend's output is impossible! Tell
me whether I got approximately correct output or my friend?
Prasoon
If you are not using dynamic formatting, using constant data,
then cout::write is about as fast as fwrite(). The whole point
is that these block write functions take the data as-is and
send it on its merry way.
My favorite Hello World program:
int main(void)
{
static const char hw[] = "Hello World!\n";
static const unsigned int LENGTH = sizeof(hw) - 1;
cout.write(hw, LENGTH);
return EXIT_SUCCESS;
}
If you take a look at your results, the timings seem to be negligible.
The difference in timings are not significant due to the OS priorities
and the speed of the platform's I/O channel(s). In other words,
the time you save here will be wasted waiting for user input,
a hard drive, internet transmission, etc.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library