views:

87

answers:

1

I time various transactions in my Java application. At the start of the transaction, I get a start time by instantiating a Calendar and then getting the hour, minute, second, and millisecond. I complete the transaction, instantiate a new Calendar and get a new hour, minute, second, and millisecond. My reasoning is that the difference between the start time and the end time is the time of the transaction. This seems to work most of the time, but a tiny fraction of the time, the end time is earlier than the start time. Why would this occur and how can I prevent it?

+6  A: 

Well, for one thing a simpler way of computing the difference would be to use something like System.currentTimeMillis() or System.nanoTime() - that way you don't need to do anything other than just a simple subtraction to get the number of milliseconds or the number of nanoseconds between the start and the end.

However, if your system clock is being updated by NTP or something similar, then time may effectively go backwards occasionally - depending on how clock skew is handled. (Some systems just slow down the system clock for a while to skew it back to reality; others may have discontinuities.)

I'm not sure of the best way of avoiding this - I don't believe the JRE currently has anything equivalent to Stopwatch in .NET, which is purely for measuring intervals and doesn't (I believe) get messed up by the system clock changing.

(I go along with Erick's recommendation of Joda Time, btw - although I don't think you need it for this particular problem.)

Jon Skeet
This is a great answer.
Erick Robertson
From my experience, timing is much more precise on linux than windows. System.currentTimeInMilis tends to skip forward in bigger chunks on windows... Not sure if that will matter, but it could
bwawok