Why std::cout is faster than printf?
C++ standards recommends using std::cout instead of printf but some c++ tips and tricks youtubers say to use printf. Read the article carefully to clear your doubts.
If you are a competitive programmer at LeetCode or HackerRank, you must be thinking why your code is not much faster even if you are using printf and scanf function but guys I want to tell you that std::cout is already optimized at maximum level.
Just Run the below code and you will know :
#include <iostream>
#include <iomanip>
#include <vector>
#include <cstdio>
#include <ctime>
int main(){
std::cout << std::setprecision(5);
// pushing 10,000 values to the vector
std::vector<int> vec;
for (int i = 0; i < 10000; ++i){
vec.push_back(i);
}
// saving the time before start printing
clock_t start = clock();
// printing the vector using std::cout
for (const auto &i : vec){
std::cout << i << '-';
}
// saving the time after start printing
clock_t end = clock();
// saved time taken by std::cout
auto t1 = double(end - start) / double(CLOCKS_PER_SEC);
start = clock();
// printing the vector using printf
for (const auto &i : vec){
printf("%d-", i);
}
end = clock();
// saved time taken by printf
auto t2 = double(end - start) / double(CLOCKS_PER_SEC);
std::cout << "\n > Time taken by std::cout : " <<t1;
printf("\n > Tim taken by printf : %.5lf", double(end - start) / double(CLOCKS_PER_SEC));
return 0;
}
The Result in my system is given below :
> Time taken by std::cout : 0.873
> Time taken by printf : 1.40300
Now, the question arises why std::cout is faster than printf ? The answer of this question is available is the following points:
1. Buffering: By default, std::cout is synchronized with the standard C output stream (stdout), meaning it flushes its buffer after every output operation. In contrast, printf does not automatically flush its buffer, which can lead to output being delayed until the buffer is flushed explicitly or automatically by other means. This can give the impression that std::cout is faster since the output appears immediately.
2. Locale Support: std::cout supports localization and is aware of the locale settings, which can impact the formatting of output (e.g., handling of decimal separators, date formats). printf does not have built-in support for locale settings and may require additional formatting instructions to achieve the same results, potentially impacting performance.
3. Inline Implementation: Modern C++ compilers often inline the implementation of std::cout, optimizing it for performance in many cases. This means that the code generated by using std::cout can be more efficient than the function call overhead associated with printf.
So, if you find this blog helpful and knowledgeable, then do subscribe to this substack.
Author: Saksham Joshi [Linkedin]