A couple of days ago I did a test on If Statements vs. Switch Statements and said I’d be providing more benchmark tests later on. This test involves the printf and cout functions. Both produce the same exact results but will they be comparable in speed? Again, at the bottom of the page you can download the source code for this test.
Note: I am/will be using the Code::Blocks IDE to perform my benchmark tests which uses the MingW / GNU GCC compiler. Using a different compiler or IDE may provide slightly different results.
Let’s take a look at the functions first:
void TestOne(){
for(int i = 0; i < 100; i++){
printf("This is the value: %d\n", val);
}
}
void TestTwo(){
for(int i = 0; i < 100; i++){
cout << "This is the value: " << val << "\n";
}
}
In this case, val represents an integer stored as a global variable. For this test each function is executed 100 times and each function outputs a string to the console 100 times within a loop. Here’s the results:

printf is an amazing 46.4% faster over cout
printf has such an improvement over cout I decided to run the test several more times. Even then printf still had a time between 12-16 ms. while cout had 26-30 ms. times. As a result of this test, I’d highly recommend using the printf function over the cout function whenever possible. I have personally preferred using it anyway because I enjoy the way you can insert multiple variables into the function and use little space in comparison to cout. Also, the printf function has a useful brother, sprintf which works almost exactly like printf except for the fact it stores the result in a variable rather than printing it to the console (but that is for another day).
Additional notes: It was brought to my attention by a frequent visitor that timings may vary quite a bit. It is my assumption this is due to hardware or even quite possibly, choice of OS. For these tests I am running Vista x64 with 8GB of ram and an Intel Core2Quad @ ~2.67 ghz.
Stay tuned for more tests!
Download source code

Home
Projects
Hosting
Advertising
About
Archive
Contact
Forums
Subscribe
I don’t get the same results. I first ran your executable to get the timings: 25, 20; 28, 27; 26, 25; 27, 28; 28, 27; So basically no difference there.
I then compiled my own using mingw to get the timings: 29, 26; 28, 26; 28, 24; 26, 29; 27,27; so no real differences here either. I also tried enabling the optimization flags but this had no effect.
The visual c++ compiler would not compile the code for me.
Reply
Interesting. I wonder if this is due to system specs? What kind of machine do you have? I’m running an Intel Core 2 Quad @ 2.66 ghz / 8 gb of ram with Vista x64. It could possibly be due to the OS as well?
Reply
I have a Pentium 4 Willamette processor (2.26Ghz) with 768Mb RAM and XP Home 32 bit.
Reply