Open In App

Why we should avoid using std::endl

Improve
Improve
Like Article
Like
Save
Share
Report

It is a common practice to use std::endl to print newlines while using cout. For small programs with very little I/O operations this practice is acceptable, but if the bulk of I/O operations increase, then the efficiency of the program is compromised.

std::endl not only adds newlines to the stream, it also flushes the buffer each time it is used.Thus when we write

 cout << std::endl; 

We are actually doing something like this

 cout << '\n' << std::flush; 

Flushing of buffers is an Operating System task. Each time the buffer is flushed, a request has to be made to the OS and these requests are comparatively expensive. Furthermore, we don’t really need to flush the buffer every time we write something to the stream, since the buffers get flushed automatically when they get full. In the rare cases we do need to perform flushing, we can explicitly specify the operation using either cout.flush() or by inserting std::flush into the stream.

Writing ‘\n’ characters directly to the stream is more efficient since it doesn’t force a flush like std::endl.

Demonstration of performance impact
The following C++ program demonstrates the performance impact of std::endl. We write 100000 strings to two files once using std::endl and then again using ‘\n’. In each case, we measure the execution time taken and print these times




#include <iostream>
#include <chrono>
#include <fstream>
using namespace std;
using namespace std::chrono;
  
int main()
{
  ofstream file1("file1.txt");
  ofstream file2("file2.txt");
  
  
  // Write to file1 using endl 
  // To measure execution time in C++ 
  // refer to this article 
  
  auto start = high_resolution_clock::now();
  for ( int i = 0; i < 100000; i++) {
    file1 << "Hello World " << std::endl ;
  }
  auto stop = high_resolution_clock::now();
  auto duration = duration_cast<microseconds>(stop-start);
  
  cout << "Writing to file using endl took "  
    << duration.count() << " microseconds" << std::endl;
  
  // Write to file2 using \n 
    
  start = high_resolution_clock::now();
  for ( int i = 0; i < 100000; i++) {
    file2 << "Hello World \n" ;
  }
  stop = high_resolution_clock::now();
  duration = duration_cast<microseconds>(stop-start);
  
  cout << "Writing to file using \\n took " 
    << duration.count() << " microseconds"<< std::endl;
  
  file1.close();
  file2.close();
  
  return 0;
}


Output: (Machine Dependent)

Writing to file using endl took 3272 microseconds
Writing to file using \n took 1533 microseconds

As seen from the output std::endl took nearly double the time. On some systems, the performance impact could be even worse. Note that it is guaranteed that std::endl will take more time than printing ‘\n’ directly to the stream.

References:
C++ Weekly – Episode 7



Last Updated : 27 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads