Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java System.nanoTime() huge difference in elapsed time

I'm in and android widget and checking elapsed time between two calls of System.nanoTime() and the number is huge. How do you measure elapsed time with this? it should be a fraaction of a second and instead its much more. Thanks

like image 565
Androider Avatar asked Feb 16 '11 23:02

Androider


People also ask

Is system nanoTime () reliable?

nanoTime() is a great function, but one thing it's not: accurate to the nanosecond. The accuracy of your measurement varies widely depending on your operation system, on your hardware and on your Java version. As a rule of thumb, you can expect microsecond resolution (and a lot better on some systems).

How accurate is system currentTimeMillis?

currentTimeMillis() actually give the time accurate to the nearest millisecond on Linux, Mac OS and Windows (and since which versions - I know, for example, that Windows only used to be accurate to the nearest 15/16 milliseconds).

What does system nanoTime do in Java?

nanoTime. Returns the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds. This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.

Is system nanoTime unique?

nanoTime() will return a unique value.


2 Answers

The System.nanoTime() returns a time value whose granularity is a nanosecond; i.e. 10-9 seconds, as described in the javadoc. The difference between two calls to System.nanoTime() that are a substantial fraction of a second apart is bound to be a large number.


If you want a time measure with a larger granularity, consider System.currentTimeMillis() ... or just divide the nanosecond values by an appropriate power of 10 to suit your application.

Note that on the Android platform there are 3 distinct system clocks that support different "measures" of time; see SystemClock. If you are programming explicitly for the Android platform, you should read the javadoc and decide which measure is most appropriate to what you are doing.


For your information, "nano-" is one of the standard prefixes defines by the International System of Units (SI) - see http://physics.nist.gov/cuu/Units/prefixes.html.

If you really think that "they" got it wrong and that "nano-" is too small, you could always write a letter to the NIST. I'm sure someone would appreciate it ... :-)

like image 86
Stephen C Avatar answered Oct 13 '22 23:10

Stephen C


One seconds contains 1,000,000,000 nanoseconds, so as long as your number is in that range, it's reasonable.

like image 45
iluxa Avatar answered Oct 13 '22 22:10

iluxa