I wrote a numerical simulation and, as a tweak, I wanted to add some basic progress bar.
In the main loop I wrote:
if(particles.t>=pr*maxtime){
cout << "|";
pr+=0.01;
}
Where pr starts at 0.01. So, basically it was supposed to cout one hundred "|" during the computation. Instead of that it couts these "|" at the end of the simulation, all at once.
And when I modify this code to:
if(particles.t>=pr*maxtime){
cout << pr << "\n";
pr+=0.01;
}
it works as it should.
I guess it have something to do with optimization, I am compiling my code using g++, with options -Wall and -lm. Code like this worked when I wrote it in C#, a while ago.
The problem is with the buffering of the output. Place cout.flush(); after each printing and the issue should be solved.
The writes to cout (and many other streams) are buffered. If you want to make them immediately visible, you need to flush the stream:
if(particles.t>=pr*maxtime){
cout << "|";
cout.flush();
pr+=0.01;
}
Related
I'm testing C++ code for stream buffering. As far as my understanding goes for buffering idea, the following code should print out "Before loop " and "After loop" at the same time, even though there is delay in form of for loop. Problem is that it prints them with that loop delay. Can someone explain the reason to me? I'm passing cout as an argument.
void testBuffer(ostream& os){
os << "Before loop - ";
for(int i = 0; i < 2000000000; i++){
// waste time
}
os << "After loop " << endl;
}
Buffers are not infinite, and in the case of non-file streams probably not even all that large.
Just because you did not write std::flush doesn't mean there definitely won't be an immediate response from the stream. If the buffer is full, it's still going to flush. It's just that you're not forcing an early flush.
Furthermore you may conceivably see std::cout behaving like std::cerr (which basically disables buffering) in debug modes. I don't know whether any implementation does this.
Moral of the story:
if you need the output immediately, flush;
if you need it later, write it later;
if and only if you don't care either way, do it the way you've done it.
This question already has answers here:
endl and flushing the buffer
(5 answers)
Closed 6 years ago.
std::cout << "Enter two numbers:";
std::cout << std:endl;
This code snippet is followed by two paragraphs and a warning note, among which I understood the first para, but neither the second one nor the note. The text is as follows -
"The first output operator prints a message to the user. That message
is a string literal, which is a sequence of characters enclosed in
double quotation marks. The text between the quotation marks is
printed to the standard output.
The second operator prints endl,
which is a special value called a manipulator. Writing endl has
the effect of ending the current line and flushing the buffer
associated with that device. Flushing the buffer ensures that all the
output the program has generated so far is actually written to the
output stream, rather than sitting in memory waiting to be written.
Warning Programmers often add print statements during debugging. Such statement should always flush the stream. Otherwise, if the
program crashes, output may be left in the buffer, leading to
incorrect inferences about where the program crashed."
So I didn't understand of the part of endl, nor the following warning. Can anyone please explain this to me as explicitly as possible and please try to keep it simple.
Imagine you have some code that crashes somewhere, and you don't know where. So you insert some print statements to narrow the problem down:
std::cout << "Before everything\n";
f1();
std::cout << "f1 done, now running f2\n";
f2();
std::cout << "all done\n";
Assuming that the program crashes during the evaluation of either f1() or f2(), you may not see any output, or you may see partial output that is misleading -- e.g. you could see only "Before everything", even though the crash happened in f2(). That's because the output data may be waiting in a buffer and hasn't actually been written to the output device.
The Primer's recommendation is therefore to flush each output, which you can conveniently achieve with endl:
std::cout << "Before everything" << std::endl;
f1();
std::cout << "f1 done, now running f2" << std::endl;
f2();
std::cout << "all done" << std::endl;
An alternative is to write debug output to std::cerr instead, which is not buffered by default (though you can always change the buffering of any ostream object later).
A more realistic use case is when you want to print a progress bar in a loop. Usually, a newline (\n) causes line-based output to be printed anyway, but if you want to print a single character for progress, you may not see it printed at all until after all the work is done unless you flush:
for (int i = 0; i != N; ++i)
{
if (i % 1000 == 0)
{
std::cout << '#'; // progress marger
std::cout.flush();
}
do_work();
}
std::cout << '\n';
Well, simply:
std::cout << "Hello world!";
will print "Hello world!" and will remain in the same line. Now if you want to go to a new line, you should use:
std::cout << "\n";
or
std::cout << std::endl;
Now before I explain the difference, you have to know 1 more simple thing: When you issue a print command with the std::cout stream, things are not printed immediately. They are stored in a buffer, and at some point this buffer is flushed, either when the buffer is full, or when you force it to flush.
The first kind, \n, will not flush, but the second kind std::endl, will go to a new line + flush.
Operating systems do buffered IO. That is, when your program outputs something, they dont necessarily put it immediately where it should go (i.e. disk, or the terminal), they might decide to keep the data in an internal memory buffer for some while before performing the actual IO operation on the device.
They do this to optmize performance, because doing the IO in chunks is better than doing it immediately as soon as there are a few bytes to write.
Flushing a buffer means asking the OS to perform immediately the IO operation without any more waiting. A programmer would do this this when (s)he knows that waiting for more data doesn't make sense.
The second note says that endl not only prints a newline, but also hints the cout to flush its buffer.
The 3rd note warns that debugging errors, if buffered and not flushed immediately, might not be seen if the program crashes while the error messages are still in the buffer (not flushed yet).
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.
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).
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');
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.
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.
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));
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.
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.
I often use cout for debugging purpose in many different places in my code, and then I get frustrated and comment all of them manually.
Is there a way to suppress cout output in the runtime?
And more importantly, let's say I want to suppress all cout outputs, but I still want to see 1 specific output (let's say the final output of the program) in the terminal.
Is it possible to use an ""other way"" of printing to the terminal for showing the program output, and then when suppressing cout still see things that are printed using this ""other way""?
Sure, you can (example here):
int main() {
std::cout << "First message" << std::endl;
std::cout.setstate(std::ios_base::failbit);
std::cout << "Second message" << std::endl;
std::cout.clear();
std::cout << "Last message" << std::endl;
return 0;
}
Outputs:
First message
Last message
This is because putting the stream in fail state will make it silently discard any output, until the failbit is cleared.
To supress output, you can disconnect the underlying buffer from cout.
#include <iostream>
using namespace std;
int main(){
// get underlying buffer
streambuf* orig_buf = cout.rdbuf();
// set null
cout.rdbuf(NULL);
cout << "this will not be displayed." << endl;
// restore buffer
cout.rdbuf(orig_buf);
cout << "this will be dispalyed." << endl;
return 0;
}
Don't use cout for debugging purposes, but define a different object (or function, or macro) that calls through to it, then you can disable that function or macro in one single place.
You can user cerr - standard output stream for errors for your debug purposes.
Also, there is clog - standard output stream for logging.
Typically, they both behave like a cout.
Example:
cerr << 74 << endl;
Details: http://www.cplusplus.com/reference/iostream/cerr/
http://www.cplusplus.com/reference/iostream/clog/
If you include files which involve cout you may want to write the code at the start (outside of main), which can be done like this:
struct Clearer {
Clearer() { std::cout.setstate(std::ios::failbit); }
} output_clearer;
It seems you print debug messages. You could use TRACE within Visual C++/MFC or you just might want to create a Debug() function which takes care of it. You can implement it to turn on only if a distinct flag is set. A lot of programs use a command line parameter called verbose or -v for instance, to control the behavior of their log and debug messages.
I am currently using Visual Studio 2013. I've never used the debugger for my C++ code before, but I used to use it all the time for programming my MSP430. Anyways, I'm trying to get back into programming and trying to use the debugger to step through my code and follow the logic of my if/else statements. When I try to use the debugger to do this, once it begins going into all of the prewritten C++ code for terms such as if, #include, ect. I am trying to get my debugger to ignore all of the standard C++ behind the scenes details, and just step through my code. I messed with Microsoft "My Code Only" feature, but can't seem to get it to do what I desire. Worst case, I guess I have to set a breakpoint after after line I want to go through, but was curious if there was an easier method. Thanks!
UPDATE:
Here is the example code I am using to test your suggestions.
#include <iostream>
#include <string>
using namespace std;
int main(){
cout << "line one\n";
cout << "line one\n";
cout << "line one\n";
cout << "line one\n";
cout << "line one\n";
cout << "line one\n";
cout << "line one\n";
cout << "line one\n\n";
string input;
cin >> input;
cout << "line one";
cout << "line one";
cout << "line one";
return 0;
}
It's nothing pretty, but I'm trying to just step from the first cout statement, see it displayed in my console window, click a button, have it display the next cout statement, repeat, well repeatedly.
I'm sure I'm just not implementing the suggestions correctly. When I try the step out method, it ends up running all of my cout statements. Is this just because I'm trying to do a cout operation, instead of a logic tree, such as if/whiles/ ect?
Here's the illogical mess I'm actually trying to use this method to trace my path through the logic. It's pretty bad code, but before I scrap it and rewrite it, I was trying to figure out how to step through it and trace the mess.
#include <iostream>
#include <string>
using namespace std;
int main(){
string action;
bool running = 1;
int turn = 1;
while (running){
//display map
if (turn == 1){
//ask for user input
cout << "Choose a planet (ex: A1 or D4) or END turn: ";
cin >> action;
if (action == "END"){
if (turn == 1){
turn = 2;
}
else {
turn = 1;
}
}
}
else{
cout << "It is not your turn";
turn = 2;
}
//change players turn
}
return 0;
}
I'm trying to step through my nested conditionals, because when I run the code it just prints "It is not your turn" for ever. I'm pretty sure I know the real reason it does this, but debugging this snippets not the purpose of the question. :)
When stepping through the code with MSVC debugger you usually have two options (to be used after setting a breakpoint or having your debugger started and your program paused somehow):
Step into (shortcut F11)
Step out (shortcut F10)
the first enters in detail into function calls, operator overrides, object construction and doesn't leave an instruction until everything has been "stepped through", while the latter is what you want: a "high level" overview that just skips everything in which an instruction can be decomposed and "jumps" to the next instruction.
The "Just my code" used to be a managed-feature only but it seems they've enabled it for native C++ as well. This can be useful to avoid pestering the stack trace with lots of unnecessary entries, but the step-in and step-out mechanism still holds.
Edit: the above works IFF your app is compiled in debug mode. Release mode is an optimized version for.. well.. releasing programs to the end-users. That means it won't have debugging information and thus setting breakpoints won't work as expected.
For the code above:
Make sure you're compiling in debug mode (you can change this by going into the project properties)
Put a breakpoint on the first statement of your main() function
Launch the debugger
When the execution stops on the line you put the breakpoint into, press F10 to step to the next instruction
Notice that the execution will be passed to the program when you step over a console input operation to let you digit something on the terminal screen. It will resume in the debugger as soon as you enter the newline character.
In addition to just "stepping out" immediately after stepping into an operator or new or an accessor that is not of interest, there is also a context menu item "Step into ..." that will bring up a dialog asking which function you actually want to step into. When this works (my experience is that it is often a bit flakey), it will allow you to completely bypass other getters, operators, etc., that are used before the function call of interest is called.
Sometimes, however, the simplest thing is to set a breakpoint in the function that you want to step into and then Continue. I find this the best approach if I'm needing to do it repeatedly.