Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.


2 Answers

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);
like image 186
dierre Avatar answered Sep 30 '26 04:09

dierre


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());
like image 29
Ankit Avatar answered Sep 30 '26 05:09

Ankit



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!