There is no single procedure to achieve more performance. Performance is a little bit of each of the details!
Usually when you use an IDE they usually autocomplete your std::cout
with std::endl
and this is not a good idea!
Using std::endl
can be inefficient, as it actually does two tasks:
'\n'
;That is, using std::endl
is equivalent to using: '\n'
« std::flush
.
When writing text to the console using std::cout usually clears the output anyway (and if it doesn’t, it generally doesn’t matter), then having std::endl
flush is rarely important.
Because of this, the use of the '\n'
character is usually preferable. The '\n'
character moves the cursor to the next line, but does not make the download redundant, so it performs better. The '\n'
character also tends to be easier to read, as it is shorter and can be incorporated into existing text.
Std::endl is technically unnecessary, since the program ends immediately afterwards.
The
std::endl
can be useful only when: first, it helps to indicate that the output line is a “complete thought”. Second, if we want to add exit instructions later, we don’t have to modify the existing code. We can just add them. But in the “overwhelming” majority of cases you will not need to use it.
Let’s analyze the runtime of the program below using std::endl
and then only '\n'
:
For this we will use the
time
command to inform us of the execution time
1º Using std::endl
Execution time according to the
time
command
'\n'
Execution time according to the
time
command
That is, we had a gain of 3 seconds for every 1 million cycles, usually when a program is open it does a lot more cycles than that!
If you want to know more about the time
use command: man time
!
VIDEO TIP: This video shows the performance of programming languages verified with the time command:
Tested the Performance of 10 Ranking Programming Languages