user2925739
user2925739

Reputation:

Why my program runs fast when I make a call to System.nanoTime() outside the System.out.println statement?

My program runs 30000ns faster with this code:

long t = System.nanoTime();
...
long t2 = System.nanoTime();
System.out.println("Time: " + (t2 - t));

Than with this other:

long t = System.nanoTime();
...
System.out.println("Time: " + (System.nanoTime() - t));

In the first one, I even make another variable, why is it faster then?

Upvotes: 0

Views: 71

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533510

The second one creates a new StringBuilder and appends a String to it before taking the timings. The first one takes the timing before doing this extra work.

The second one is equivalent to

System.out.println(new StringBuilder().append("Time: ")
                   .append(System.nanoTime() - t).toString());

or

StringBuildler sb = new StringBuilder().append("Time: "); // included in timing
long time = System.nanoTime() - t;
System.out.println(sb.append(time).toString());

BTW Just performing an output to the console can disturb very short tasks and make them slower. I suggest you run the test many times, ignore the first 20K as warm up and print a summary of the results at the end.

Upvotes: 1

Related Questions