Question

In cpp reference, it claims fflush is:

Causes the output file stream to be synchronized with the actual contents of the file.

Indeed, I don't understand what it means. I just wonder, in that code, if I take out fflush, is there any difference?

I tested it, it seems there is a little bit difference, but I can't find the pattern. Could any one explain it in details for me? Thanks in advance.

#include<stdio.h>
int i;

int main()
{
    fork();
    for(i=0;i<1000;i++)
    {
        printf("%d\n",i);
        fflush(stdout);// without fflush, is there any difference?
    }
}
Was it helpful?

Solution

The standard output is normally flushed when you write a newline. If you want to test this properly, open a file and write to it. For your tests to be useful, you will have to write a lot more data than just a few integers. You should find that omitting fflush will result in significantly faster code. Try timing these two loops...

With flushing:

FILE * fp = fopen("scratch", "w");
for( int i = 0; i < 1000000; i++ ) {
    fprintf( fp, "Hello world" );
    fflush(fp);
}
fclose(fp);

Without flushing:

FILE * fp = fopen("scratch", "w");
for( int i = 0; i < 1000000; i++ ) {
    fprintf( fp, "Hello world" );
}
fclose(fp);

On my machine, the results are:

With fflush:    4.57 seconds
Without fflush: 0.24 seconds
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top