P. Balech
P. Balech

Reputation: 125

Why cerr output faster than cout?

Using cout needs a little bit more time to output the statement which isn't good for me. But when using cerr the output is faster. Why?

Upvotes: 3

Views: 2773

Answers (1)

Deni Pramulia
Deni Pramulia

Reputation: 69

Just trying to help : - cout -> Regular output (console output) - cerr -> Error output (console error)

cout is buffered, cerr is not, so cout should be faster in most cases. (Although if you really care about speed, the C output functions such as printf tend to be a lot faster than cout/cerr). cout and cerr are ostream objects. You can call rdbuf() on them to redirect their output independently wherever you want, from within the application. You can open a network socket, wrap it in a stream buffer and redirect there, if you want.

By default, cout is tied to the application's standard output. By default, the standard output is the screen. You can direct the OS to redirect stdout elsewhere. Or it might do it by itself - the nohup utility in Linux, for example, does. Services in Windows also have their standard streams redirected, I think.

And, cerr are tied to the application's standard error. By default the standard error is the screen. You can again redirect stderr elsewhere. Another issue here is that clog, by default, is buffered like cout, whereas cerr is unit-buffered, meaning it automatically calls flush() after every complete output operation. This is very useful, since it means that the output is not lost in the buffer if the application crashes directly afterwards.

If you run a program like this: yourprog > yourfile

What you write to cout will go to yourfile. What you write to cerr will go to your screen. That's usually a good thing. I probably don't want your error messages mixed in with your program output. (Especially if some of your error messages are just warnings or diagnostic stuff). It's also possible to redirect cout to 1 file, and cerr to another. That's a handy paradigm: I run your program, redirect output to a file, error messages to a different file. If your program returns 0 from main, then I know it's OK to process the output file. If it returns an error code, I know NOT to process the output file. The error file will tell me what went wrong.

reference : - http://www.tutorialspoint.com/cplusplus/cpp_basic_input_output.htm - http://cboard.cprogramming.com/cplusplus-programming/91613-cout-cerr-clog.html

Upvotes: 3

Related Questions