Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ does printing to terminal significantly slow down code?

I have a code where I currently print a lot of diagnostic messages to terminal. Does anybody have any idea how much this slows down my code? Would I get a big speed increase by piping the output to file, e.g. instead of running:

./my_program

i run

./my_program > output.log

Also, would I get a further speed increase by replacing cout with ofstream and writing to file directly?

EDIT: Let's assume I am writing to /dev/shm, disk access speed not really an issue.

like image 694
user788171 Avatar asked Jul 14 '12 21:07

user788171


People also ask

Does printing make code slower?

It will be slower as you are having to perform a large number of prints, any extra processing is going to incur some performance penalty. Send item to a socket queue : the program will finish the writes first, and the console from the socket will print the output with a lag.

Is writing to file faster than printing?

Writing to the console is faster, but if the write operation is all that's performed, then a program writing to a file will probably finish first.

Why is writing stdout slow?

When we are directly writing outputs to our terminal, each writing operation is being done “synchronously”, which means our programs waits for the “write” to complete before it continues to the next commands. Each time our programs writes something to stdout , we are met with this delay.

Does cout slow program?

It's almost certainly true. Writing to the terminal is notorious for slowing things down. Run your program and redirect the output to a file and see how much faster it is.


2 Answers

Yes, rendering to screen takes longer than writing to file.
In windows its even slower as the program rendering is not the program that is running, so there are constantly messages sent between processes to get it drawn.
I guess its same in linux since virtual terminal is on a different process than the one that is running.

like image 125
Dani Avatar answered Sep 21 '22 18:09

Dani


It certainly can be. Printing to a terminal involves rendering and other things (non-trivial) and is typically buffered a lot less. The OS and stream implementation can do a lot more buffering and caching with file I/O.

like image 31
Puppy Avatar answered Sep 17 '22 18:09

Puppy