Search code examples
cfflush

Using fflush for speeding up code to prevent a time limit exceeded


The following code gets TLE (time limit exceeded) if the standard output is not flushed.

#include<stdio.h>
int main(){
    int a;
    while(1){
        scanf("%d",&a);
        printf("%d\n",a);
        fflush(stdout);
        if(a==42)
            break;
    }
    return 0;
}

How does flushing the output buffer help to overcome TLE?
This is the problem link - https://www.spoj.com/problems/EXPECT/


Solution

  • The problem specification tells you what to do:

    Attention: the program should clear the output buffer after printing each line.

    It can be done using fflush(stdout) command or by setting the proper type of buffering at the beginning of the execution - setlinebuf(stdout).

    The problem title indicates why:

    (Interactive)

    The judging software is operating the program interactively. After giving the program an input, it waits for output before providing more input. When your program does not flush the buffered output, the judging software keeps waiting until its time limit is exceeded.

    Commonly, output streams to terminals are line-buffered, in which case printing a new-line character causes them to be flushed. However, this judging software is likely using a pipe that is fully buffered, so output will not be flushed until the buffer is full or you explicitly request a flush (or, at the start of the program, you change the buffering mode to unbuffered or line-buffered).

    When you flush the output, the judging software will see it, and then it will continue and provide more input.

    As an alternative to flushing the output after each printf, you can set the stream to line buffering mode by executing setvbuf(stdout, NULL, _IOLBF, 0); at the beginning of the program (before doing any other operation on the stream).