tags:

views:

287

answers:

2

In a Java application I want to be able to take a timestamp at the start of an operation and be able to periodically check how long the operation has been running. The catch is: I do not want to be impacted by the Network Time Protocol moving the clock around, or the admin changing the time, or anything which can abruptly adjust the time of day. I want a monotonically increasing time value. I believe this rules out java.util.Date, Time, and Calendar.

Is there some source of a monotonically increasing timestamp in the JRE?

+7  A: 

Have you considered using System.nanoTime()?

It is only meaningful in working out elapsed time between two events. Since the documentation states that it is not related to any system or wall time I believe it could be used in your sitatuion.

hhafez
Returns the current value of the most precise available system timer, in nanoseconds.
Adeel Ansari
Yes that is true, bat AFAIK nanoTime is not affected by system time, which is what is required by the questioner.
hhafez
Yup, tried it. Its working like charm. System.currentTimeMillis() gets affected by reseting systems time, but not the nanoTime. My carelessness.
Adeel Ansari
From the JavaDoc: No guarantees are made about how frequently values change. Is that something to be concerned about?
Hemal Pandya
For me, System.nanoTime would be great. I don't need high resolution, the events are seconds apart, I just need to be immune to adjustments of the system time of day. Since nanoTime was added in JVM 1.5, I'll have to make sure dropping JVM 1.4.2 support is ok with my product manager. Should be fine.
DGentry
+2  A: 

JodaTime has a class to do this. It is called Duration.

"They have no chronology or time zone, and consist solely of the millisecond duration."

Also you could set your Date stamp to Greenwich time and the Network Time Protocol should not be an issue.

WolfmanDragon
I considered JadoTime but I thought it would have been over kill when nanoTime is available.
hhafez