Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will using fflush after printf slow down your program?

Tags:

c++

c

printf

I am writing some console programs and I notice that sometimes when I use print() and my program is idle, not everything is printed out (the last few lines are missing).

Eventually something will happen and the lines do get printed, but often when I close the program the last few lines are not there.

So I did some digging and it looks like the stdout buffer is not always emptied unless certain conditions are met (new line? / line feed?).

so I have created a "myprintf()" function which wraps printf to do the following (in pseudo code):

printf(...);
fflush(stdout);

The question is, apart from the obvious extra function call overhead, is this going to slow my program down? I.e. is this a bad practice performance wise?

like image 766
code_fodder Avatar asked Jan 18 '26 22:01

code_fodder


2 Answers

Dependant on a couple of things.

If your printf ends with a newline character (\n), the stdout buffer will flush immedeatly and display all directly. This is default behaviour of the stdout buffer. So in that case flushing again would indeed slow your program down a little, albeit only a tiny amount.

Now, if you don't end on a newline character, stdout will not flush automatically and you indeed need the fflush to display things properly. It will then also slow down the program, albeit again, only a little.

You can completly avert your problem though, by setting the buffer stdout to not wait for newlines before flushing. This would make your wrapper redundant Like this:

setbuf(stdout, NULL);

Will guarantee every time there is anything in stdout it will be flushed. This will be slightly more efficient then your direct call to fflush() every time.

In conclusion, unless you are operating on very tight performance constraints, the overhead generated is negligible.

like image 130
Magisch Avatar answered Jan 20 '26 13:01

Magisch


Yes it will slow it down. If it didn't, then flushing would be the default behavior.

Judging by the tone of your post, it does not sound like you're doing the kinds of things where too much flushing would be noticeable. So unless you say why you're afraid of a slowdown, flush away.

like image 28
Adam Avatar answered Jan 20 '26 13:01

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!