2

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.

Gautham M
  • 4,816
  • 3
  • 15
  • 37

4 Answers4

5

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);
dierre
  • 7,140
  • 12
  • 75
  • 120
  • Will you exactly modify the code, so I will rum it and se if it works, this i is beginner level. –  Apr 09 '13 at 05:50
  • it's what I wrote, just do it before calling the print method. – dierre Apr 09 '13 at 05:55
  • I tried it before writing. Be aware that you won't see the red writing because now you are using the same stream of system.out – dierre Apr 09 '13 at 07:13
  • To be honest, it was println , as simple s that, but thank you for giving me an insight on how to resolve a issue if it comes out like that. –  Apr 09 '13 at 07:45
3

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());
Ankit
  • 6,554
  • 6
  • 49
  • 71
1

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

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

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

Dolda2000
  • 25,216
  • 4
  • 51
  • 92