Cout or Printf Which of the Two Has a Faster Execution Speed C++

Why does printf executes faster than cout in C++?Also scanf is slower than cin,why?

By default, cin/cout waste time synchronizing themselves with the C library’s stdio buffers, so that you can freely intermix calls to scanf/printf with operations on cin/cout.

Turn this off with

std::ios_base::sync_with_stdio(false);
Also many C++ tutorials tell you to write cout << endl instead of cout << '\n'. But endl is actually slower because it forces a flush, which is usually unnecessary. (You’d need to flush if you were writing, say, an interactive progress bar, but not when writing a million lines of data.) Write '\n' instead of endl.

Also as C++ is object-oriented , cin and cout are objects and hence the overall time is increased due to object binding.

So, a simple one liner, std::ios_base::sync_with_stdio(false); could make cin/cout faster than printf/scanf.

Hope this helps you

which is faster, and which is more flexible: printf or cout?

Short Answer

Faster : printf

More flexible : cout

Long answer

When compared to the sprintf family, the C++ streams are supposed to be slower (by a factor 6 if I recall an item of Exceptional C++, by Herb Sutter). Still, most of the time, you won't need this speed, but you need to be sure your code won't be bugged.

And it is easy to do something wrong with the printf family of functions, be it putting the wrong number of arguments, the wrong types, or even introduce potential security vulnerability (the %n specifier comes to mind) in your code.

Unless really wanting it (and then, it's called sabotage), it's almost impossible to get it wrong with C++ streams. They handle seamlessly all known types (build-ins, std::strings, etc.), and it's easy to extend it. For example, let's say I have an object "Coordinate3D", and that I want to print out its data:

#include <iostream>

struct Coordinate3D
{
int x ;
int y ;
int z ;
} ;

std::ostream & operator << (std::ostream & p_stream
, const Coordinate3D & p_c)
{
return p_stream << "{ x : " << p_c.x
<< " , y : " << p_c.y
<< " , z : " << p_c.z << " }" ;
}

int main(int argc, char * argv[])
{
Coordinate3D A = {25,42,77} ;
std::cout << A << std::endl ;
// will print "{ x : 25 , y : 42 , z : 77 }"
return 0 ;
}

The problem with the stream is that they are quite difficult to handle correctly when wanting to specify format of some data (padding spaces for numbers, for example), and that sometimes, you really really need to go fast. Then, either fall back to printf, or try some high-speed C++ alternatives (FastFormat comes to mind).

Edit: Note that Thomas' series of tests show interesting results (which I reproduced right now on my computer), that is: cout and printf have similar performances when one avoids using std::endl (which flushes the output in addition to outputing a \n).

printf more than 5 times faster than std::cout?

For a true apples-to-apples comparison, re-write your test so that the only thing changing between the test cases is the print function being used:

int main(int argc, char* argv[])
{
const char* teststring = "Test output string\n";
std::clock_t start;
double duration;

std::cout << "Starting std::cout test." << std::endl;
start = std::clock();

for (int i = 0; i < 1000; i++)
std::cout << teststring;
/* Display timing results, code trimmed for brevity */

for (int i = 0; i < 1000; i++) {
std::printf(teststring);
std::fflush(stdout);
}
/* Display timing results, code trimmed for brevity */
return 0;
}

With that, you will be testing nothing but the differences between the printf and cout function calls. You won't incur any differences due to multiple << calls, etc. If you try this, I suspect that you'll get a much different result.

C++ cout printing slowly

NOTE: This experimental result is valid for MSVC. In some other implementation of library, the result will vary.

printf could be (much) faster than cout. Although printf parses the format string in runtime, it requires much less function calls and actually needs small number of instruction to do a same job, comparing to cout. Here is a summary of my experimentation:

The number of static instruction

In general, cout generates a lot of code than printf. Say that we have the following cout code to print out with some formats.

os << setw(width) << dec << "0x" << hex << addr << ": " << rtnname <<
": " << srccode << "(" << dec << lineno << ")" << endl;

On a VC++ compiler with optimizations, it generates around 188 bytes code. But, when you replace it printf-based code, only 42 bytes are required.

The number of dynamically executed instruction

The number of static instruction just tells the difference of static binary code. What is more important is the actual number of instruction that are dynamically executed in runtime. I also did a simple experimentation:

Test code:

int a = 1999;
char b = 'a';
unsigned int c = 4200000000;
long long int d = 987654321098765;
long long unsigned int e = 1234567890123456789;
float f = 3123.4578f;
double g = 3.141592654;

void Test1()
{
cout
<< "a:" << a << “\n”
<< "a:" << setfill('0') << setw(8) << a << “\n”
<< "b:" << b << “\n”
<< "c:" << c << “\n”
<< "d:" << d << “\n”
<< "e:" << e << “\n”
<< "f:" << setprecision(6) << f << “\n”
<< "g:" << setprecision(10) << g << endl;
}

void Test2()
{
fprintf(stdout,
"a:%d\n"
"a:%08d\n"
"b:%c\n"
"c:%u\n"
"d:%I64d\n"
"e:%I64u\n"
"f:%.2f\n"
"g:%.9lf\n",
a, a, b, c, d, e, f, g);
fflush(stdout);
}

int main()
{
DWORD A, B;
DWORD start = GetTickCount();
for (int i = 0; i < 10000; ++i)
Test1();
A = GetTickCount() - start;

start = GetTickCount();
for (int i = 0; i < 10000; ++i)
Test2();
B = GetTickCount() - start;

cerr << A << endl;
cerr << B << endl;
return 0;
}

Here is the result of Test1 (cout):

  • # of executed instruction: 423,234,439
  • # of memory loads/stores: approx. 320,000 and 980,000
  • Elapsed time: 52 seconds

Then, what about printf? This is the result of Test2:

  • # of executed instruction: 164,800,800
  • # of memory loads/stores: approx. 70,000 and 180,000
  • Elapsed time: 13 seconds

In this machine and compiler, printf was much faster cout. In both number of executed instructions, and # of load/store (indicates # of cache misses) have 3~4 times differences.

I know this is an extreme case. Also, I should note that cout is much easier when you're handling 32/64-bit data and require 32/64-platform independence. There is always trade-off. I'm using cout when checking type is very tricky.

Okay, cout in MSVS just sucks :)

Does using printf( something ) or system( echo something ) cost more processing power?

printf is by far preferable, by many orders of magnitude and in every sense. It is a library function that's part of the C standard, and it makes your own program print the desired output. system on the other hand launches a new, separate process (something that takes a comparable eternity), and you still have to hope that your shell actually provides an echo command that does the same thing.

The only thing worse than calling system on echo would be to call system to invoke a compiler that compiles another program that contains printf and run that, I guess...

Don't use system.

Cause for this difference..from C++ to C?

The difference between the two programs is that the C++ version uses endl, which not only inserts a newline but flushes the buffer. The slow part of doing any output is flushing the buffer.

Both programs would probably be about the same speed if you made your C++ program use

count << i << "\n";

The following two programs achieve a similar execution time:

C-program (a.c):

#include <stdio.h>
#include <time.h>

int main()
{
clock_t start=clock();
for (int i=0; i<2000000; i++) printf("%d\n",i);
clock_t end=clock();

fprintf(stderr, "Time Elapsed: %f\n",((double)end-start)/CLOCKS_PER_SEC);
return 0;
}

Compile with: gcc -O3 -std=c99 a.c

C++-program (b.cpp):

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
clock_t start=clock();
for (int i=0;i<2000000;i++) cout << i << '\n';
clock_t end=clock();

cerr << "Time elapsed " << ((double)end-start)/CLOCKS_PER_SEC << endl;

return 0;
}

Compile with g++ -O3 b.cpp



Related Topics



Leave a reply



Submit