Getting precise elapsed time using Java to the Milisecond?

There are two factors here. First, even System.nanoTime() is not necessarily really precise - it just uses the finest clock available (and does not follow clock changes, so it never goes backwards or jumps forward). Second, your Java program is not the only program running on your computer - so your code (which essentially is the calling of the native nanoTime function and the output of the result) will take differently much time each time.

For example, it may be that one output needs more than a full millisecond while another takes only a half or less. Try to output some more digits (i.e. Divide by a smaller number), the results will be helpful to understand.

Divide by 1 million after the subtraction, and use a long literal. Long startTime = System.nanoTime(); while (true) { System.out. Println((System.nanoTime() - startTime)/1000000L); } Demo (updated): ideone.com/X5RRa.

1 That won't change the fact that the loop isn't guaranteed to execute at regular intervals, which seems to be what he's expecting. – Isaac Truett Mar 29 at 17:14 I guess what I was anticipating is that the milliseconds would go up regularly (0, 1, 2, 3, etc). The tenths and hundredths do.

You're saying this won't be the case for milliseconds? – Antillies Mar 29 at 17:19 @Antillies: you expect the loop to run exactly once per millisecond? Why?

– MДΓΓ БДLL Mar 29 at 17:21 @ Matt: I guess I was under the impression the loop would execute very quickly. But I guess I'm realizing by what you guys are saying that the time it takes the loop to execute is creating what I perceive as imprecision. Am I correct in understanding you that this isn’t imprecision but the loop not being able to print out the milliseconds as quickly as they occur because of the time the loop takes to execute?

– Antillies Mar 29 at 17:28 @Antilles: if I understand you correctly, then yes. – MДΓΓ БДLL Mar 29 at 17:48.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions