11

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.

6
  • 2
    fputc('\n', stdout)?
    – Kerrek SB
    May 13, 2016 at 19:34
  • All your examples output the newline character (optionally preceded by carriage return, depending on the operating system). Carriage return is denoted '\r'.
    – kfx
    May 13, 2016 at 19:38
  • 1
    @Harrison Tran What's the actual effect you expect? Some bindings for text formatting output might consider extending the '\r' and/or calling flush() explicitly, regardless. May 13, 2016 at 19:40
  • "@Harrison Tran" "I'm trying to find out what's the most efficient way to do this assuming nothing else matters." Could you define efficiency by any means? Performance? Easy to read? Automatic flushing? May 13, 2016 at 20:00
  • When you say "after the loop" do you mean "as the last thing to do in the loop", or "after I have completed all iterations of the loop"? Normal English usage would imply the latter - but then I don't understand why you care about performance (the impact of the work done many times in the loop will almost certainly drown anything done once, afterwards). May 13, 2016 at 20:22

7 Answers 7

12

putchar('\n') is the most simple and probably fastest. cout and printf with string "\n" work with null terminated string and this is slower because you process 2 bytes (0A 00). By the way, carriage return is \r = 13 (0x0D). \n code is Line Feed (LF).

9
  • What's the difference between carriage return and line feed? May 13, 2016 at 19:40
  • 9
    @HarrisonTran - carriage return moves the print position to the start of the current line. Line feed moves the print position down one line. Together they produce a new line. But that has nothing to do with the question you asked, and I'm baffled by their mention in this answer. May 13, 2016 at 19:43
  • 2
    @PeteBecker They are mentioned because the question initially was "how to output carriage return" and the example was with line feed.
    – i486
    May 13, 2016 at 19:48
  • 2
    @i486 - okay. You've had the rug yanked out from under you. May 13, 2016 at 19:54
  • 3
    @flatmouse - std::endl essentially does the same thing as \n, followed by flushing the output buffer. May 13, 2016 at 19:59
6

You don't specify whether you are demanding that the update to the screen is immediate or deferred until the next flush. Therefore:

if you're using iostream io:

cout.put('\n');

if you're using stdio io:

std::putchar('\n');
4
+50

The answer to this question is really "it depends".

In isolation - if all you're measuring is the performance of writing a '\n' character to the standard output device, not tweaking the device, not changing what buffering occurs - then it will be hard to beat options like

 putchar('\n');
 fputchar('\n', stdout);

 std::cout.put('\n');

The problem is that this doesn't achieve much - all it does (assuming the output is to a screen or visible application window) is move the cursor down the screen, and move previous output up. Not exactly a entertaining or otherwise valuable experience for a user of your program. So you won't do this in isolation.

But what comes into play to affect performance (however you measure that) if we don't output newlines in isolation? Let's see;

  • Output of stdout (or std::cout) is buffered by default. For the output to be visible, options include turning off buffering or for the code to periodically flush the buffer. It is also possible to use stderr (or std::cerr) since that is not buffered by default - assuming stderr is also directed to the console, and output to it has the same performance characteristics as stdout.
  • stdout and std::cout are formally synchronised by default (e.g. look up std::ios_base::sync_with_stdio) to allow mixing of output to stdout and std::cout (same goes for stderr and std::cerr)
  • If your code outputs more than a set of newline characters, there is the processing (accessing or reading data that the output is based on, by whatever means) to produce those other outputs, the handling of those by output functions, etc.
  • There are different measures of performance, and therefore different means of improving efficiency based on each one. For example, there might be CPU cycles, total time for output to appear on the console, memory usage, etc etc
  • The console might be a physical screen, it might be a window created by the application (e.g. hosted in X, windows). Performance will be affected by choice of hardware, implementation of windowing/GUI subsystems, the operating system, etc etc.

The above is just a selection, but there are numerous factors that determine what might be considered more or less performance.

4

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.

1
  • 1
    "and does not output to the device." That's not guaranteed unfortunately, and you could actually have an implementation that implies adding '\r' and triggering flush(). May 13, 2016 at 20:05
4

It's actually OS/Compiler implementation dependent.

The most efficient, least side effect guaranteed way to output a '\n' newline character is to use std::ostream::write() (and for some systems requires std::ostream was opened in std::ios_base::binary mode):

static const char newline = '\n';
std::cout.write(&newline,sizeof(newline));
2

I would suggest to use:

std::cout << '\n';  /* Use std::ios_base::sync_with_stdio(false) if applicable */

or

fputc('\n', stdout);

And turn the optimization on and let the compiler decide what is best way to do this trivial job.

0

Well if you want to change the line I'd like to add the simplest and the most common way which is using (endl), which has the added perk of flushing the stream, unlike cout << '\n'; on its own.

Example:

     cout << "So i want a new line" << endl;
     cout << "Here is your new line";

Output:

       So i want a new line
       Here is your new line

This can be done for as much new lines you want. Allow me to show an example using 2 new lines, it'll definitely clear all of your doubts,

Example:

         cout << "This is the first line" << endl;
         cout << "This is the second line" << endl;
         cout << "This is the third line";

Output:

   This is the first line
   This is the second line
   This is the third line

The last line will just have a semicolon to close since no newline is needed. (endl) is also chain-able if needed, as an example, cout << endl << endl; would be a valid sequence.

3
  • std::endl flushes the buffer. This overhead might not be desired in OP's question. In fact doing std::cout << "\n\n"; is guaranteed to be faster the std::cout << std::endl << std::endl; because std::endl will have to flush the output buffer everytime you use it. Jul 20, 2022 at 16:39
  • And that's one reason I am against C++. Side effects everywhere, gochas everywhere. Jul 20, 2022 at 16:44
  • @AhmedShaqanbi Isn't that a criticism of the standard library more than the actual language itself? Of course, it's hard to separate a language from its standard library. But theoretically, a more deterministic replacement library could in fact be created. Perhaps such an effort is already underway, I don't know.
    – Tom
    Oct 20, 2023 at 13:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.