Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to output a newline

Tags:

c++

I was wondering what is the most efficient performant way to output a new line to console. Please explain why one technique is more efficient. Efficient in terms of performance.

For example:

cout << endl;
cout << "\n";
puts("");
printf("\n");

The motivation for this question is that I find my self writing loops with outputs and I need to output a new line after all iterations of the loop. I'm trying to find out what's the most efficient way to do this assuming nothing else matters. This assumption that nothing else matters is probably wrong.

like image 474
Harrison Tran Avatar asked May 13 '16 19:05

Harrison Tran


1 Answers

On Ubuntu 15.10, g++ v5.2.1 (and an older vxWorks, and OSE)

It is easy to demonstrate that

std::cout << std::endl;

puts a new line char into the output buffer, and then flushes the buffer to the device.

But

std::cout << "\n";

puts a new line char into the output buffer, and does not output to the device. Some future action will be needed to trigger the output of the newline char in the buffer to the device.

Two such actions are:

std::cout << std::flush;  // will output the buffer'd new line char

std::cout << std::endl;   // will output 2 new line chars

There are also several other actions that can trigger the flush of the std::cout buffering.


#include <unistd.h>  // for Linux
void msDelay (int ms) { usleep(ms * 1000); }

int main(int, char**)
{
   std::cout << "with endl and no delay " << std::endl;

   std::cout << "with newline and 3 sec delay " << std::flush << "\n";
   msDelay(3000);

   std::cout << std::endl << " 2 newlines";
   return(0);
}

And, per comment by someone who knows (sorry, I don't know how to copy his name here), there are exceptions for some environments.

like image 174
2785528 Avatar answered Oct 11 '22 00:10

2785528