Consider the following code
package tests;
public class Test_computer_speed {
public static void main(String[] args) {
for(int i=0; i<10; ++i) {
testMillis();
}
for(int i=0; i<10; ++i) {
testNanos();
}
}
public static void testMillis() {
long startTime = System.currentTimeMillis(), endTime = startTime + 6000, iterations = 0, now;
while (true) {
now = System.currentTimeMillis();
if (now > endTime)
break;
iterations++;
}
System.out.println("In 6 seconds, the loop performed " + iterations + " iterations.");
}
public static void testNanos() {
long startTime = System.nanoTime(), endTime = startTime + 6000000000l, iterations = 0, now;
while (true) {
now = System.nanoTime();
if (now > endTime)
break;
iterations++;
}
System.out.println("In 6 seconds, the loop performed " + iterations + " iterations.");
}
}
output follows:
>java tests.Test_computer_speed
In 6 seconds, the loop performed 1402955969 iterations.
In 6 seconds, the loop performed 1452564156 iterations.
In 6 seconds, the loop performed 1443087123 iterations.
In 6 seconds, the loop performed 1417403052 iterations.
In 6 seconds, the loop performed 1451880195 iterations.
In 6 seconds, the loop performed 1444997459 iterations.
In 6 seconds, the loop performed 1438911291 iterations.
In 6 seconds, the loop performed 1461714025 iterations.
In 6 seconds, the loop performed 1460849690 iterations.
In 6 seconds, the loop performed 1441407031 iterations.
In 6 seconds, the loop performed 512124051 iterations.
In 6 seconds, the loop performed 524528348 iterations.
In 6 seconds, the loop performed 525100685 iterations.
In 6 seconds, the loop performed 528140105 iterations.
In 6 seconds, the loop performed 526142121 iterations.
In 6 seconds, the loop performed 526086430 iterations.
In 6 seconds, the loop performed 530290126 iterations.
In 6 seconds, the loop performed 529469812 iterations.
In 6 seconds, the loop performed 528229751 iterations.
In 6 seconds, the loop performed 529689093 iterations.
This means that nanoTime()
function is 10 times slower, than currentTimeMillis
.
What is the sense of having more precise function if it is slower?
In other words, Java is cheating, probably gaining precision by waiting for some time on call.
UPDATE
Look at uncertainty. The nanoTime() speed is 10 times slower, and the uncertainty is 10 times better.
This means, that absolute uncertainty IS THE SAME.