Question

I am using system.nanoTime in my app and I calculate time relative to a starttime.
My app ran very well until I copied it to a new computer and on it the nano time gives me slower values.

I wrote a simple app just to make sure.
the nano time is compared to the system time.
It shows the same values in other computers except my new one . any suggestions?

Here is my code: First I have

private long initNanoTime = System.nanoTime();
private long initTime = System.currentTimeMillis();

than I loop a thread that runs every second:

long timeUsingNanoTime = initTime + (System.nanoTime() - initNanoTime) / 1000000;
long timeUsingMilis = System.currentTimeMillis();
long nanotimeOffset = Math.abs(timeUsingNanoTime - timeUsingMilis);
if (nanotimeOffset < 100l) ? print("close") : print(far);

Edit : I am using nano because I need to handle even ts that occur in nano time and print to a log the nano time which it was received in

Was it helpful?

Solution

It's like the Java API docs say about System.nanoTime():

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.

This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) - no guarantees are made except that the resolution is at least as good as that of currentTimeMillis().

It does not provide any coupling with the timestamp (currentTimeMillis) and does not provide a fixed resolution.

In your case it seems that Java now has a higher resolution timer available than before, and so does not need to use the system time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top