简体   繁体   中英

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.

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);

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());

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM