I've been searching for an answer to my dilemma and have found some useful tips but nothing that addresses my specific question, so I was hoping someone here might be able to help me out.
I'm trying to get a precise elapsed time to the millisecond in Java. I'm using System.nanoTime() to get the current time and implementing it in the following code. Mind you, this was code that I used to test it's precision.
long startTime = System.nanoTime()/1000000;
while (true)
{
System.out.println((System.nanoTime()/1000000)-startTime);
}
A portion of the output looks like this.
1110
1112
1112
1113
1114
1118
1120
The first digit is the number of seconds, the second, tenths of a second, the third, hundredths, and then the last is thousandths. You can't see it here, but I have precision to the hundredths place - no skipped or repeated numbers. The thousandths, though, is far from precise. 0 -> 2 -> 2 -> 3 -> 4 -> 8 -> 0. For what I'm doing, I need precision to the thousandths place and from all I have read it seems like System.nanoTime() should be able to provide precision to the millisecond.
Am I doing something wrong or is there another way I can get precision to the millisecond?
Divide by 1 million after the subtraction, and use a
long
literal.Demo (updated): http://ideone.com/X5RRa