System.out.err & System.out interleaving in Java

670 Views Asked by At

To work out how much time is taken to perform an algorithm, I do this in the main method, but it does not print the time as it gets interleaved with System.print.

long startTime = System.currentTimeMillis();     
A1.Print(2);
long endTime = System.currentTimeMillis();
System.err.print(endTime - startTime);

and if the class A is this:

public class A{

    public void Print(int n){
        for(int i = 0; i <=n; i++){
        System.out.println(i)
    }
}

it prints

0

1

2

and in this line it is the amount of time that is supposed go through that loop, but it simply won't, so it won't print like this:

0

1

2

1

Here the last line or 1 is the millisecond taken for the algorithm. The textbook says you MUST use System.err. and figure out a way to prevent interleaving.

4

There are 4 best solutions below

2
Dolda2000 On

You should probably be using System.err.println instead of System.err.print. It might simply be buffering until it gets an entire line.

4
dierre On

You could do something like

System.setErr(System.out);

so the output is in the same stream. They use two different streams so that's why you get interleaving.

For your code it would be:

long startTime = System.currentTimeMillis();    
System.setErr(System.out); 
A1.Print(50);
long endTime = System.currentTimeMillis();
System.err.print(endTime - startTime);
0
Evgeniy Dorofeev On

If you are in Eclipse it's a known bug: https://bugs.eclipse.org/bugs/show_bug.cgi?id=32205. Try the same from command line

0
Ankit On

System.err & System.out use different buffer (dependent on OS), so these buffer might get flushed at different time. thus might give interleaving output.

And also, System.err is not guaranteed to be directed to console by default (unlike System.out), it might be linked to console or file-system.

To resolve this, you might want System.err to link to System.out

like

System.setErr(System.out);

or

System.setErr(System.console());