user3788040
user3788040

Reputation: 381

running time of flush() for output stream

I am trying to submit solution (using some online compiler that has compile time constraints) for sorting an array- here is my code snippet-

class TSORT {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter bw = new PrintWriter(System.out, false);
        int t = Integer.parseInt(br.readLine());
        int[] list = new int[1000001];      
        for(int i = 0; i < t; i++){
            int n = Integer.parseInt(br.readLine());
            list[n]++;
        }
        int r=0;
        for(int i = 0; i < 1000001; i++){
            if(list[i] > 0){

                for(int j = 0; j < list[i]; j++){
                    bw.println(i);      // if I use bw.flush() here, time limit gets exceeded.

                }
            }
    }
        bw.flush();
    }
}

This code gets submitted successfully, but if I use flush() as true (automatic flushing- new PrintWriter(System.out, true);), the compiler shows TIME LIMIT EXCEEDED .

My question is - how should I use flush() to get best compile time?

Upvotes: 2

Views: 263

Answers (1)

peter
peter

Reputation: 15139

You're submitting the code, and it is afterwards executed somewhere, that's why you have a TIme Limit Exceeded exception.

The reason why you don't get this exception if you disable automatic flushing is simple, once you look at what flush actually means. flush blocks your code and waits until everything which was written to the stream also went through the stream to it's target (in this case System.out).

If you have automatic flushing turned on, it will flush after every println command. So after every println you application blocks and waits for the Java VM or the Host system to forward your string to System.out.

If you have automatic flushing turned off, the strings of println are cached in memory. Depending of the implementation of the stream, it can still try to flush out data from the memory in the background, but it doesn't have to. In the end of your application you will write all your strings at once (via flush). This is faster because of less context switches and because it doesn't lock your application from running the loop.

Upvotes: 3

Related Questions