Java System.nanoTime() huge difference in elapsed time
Asked Answered
M

3

8

I'm in an 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 fraction of a second and instead it's much more. Thanks

Messidor answered 16/2, 2011 at 23:55 Comment(1)
Um... do you know what a nanosecond is?Thimerosal
M
20

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 ... :-)

Mf answered 17/2, 2011 at 0:17 Comment(3)
Android docs recommend SystemClock.uptimeMillis() for interval timing. Since that is what most built-in functions use, there is strong motivation for it to be well-implemented on all devices. See discussion in SystemClockKareykari
or SystemClock.elapsedRealtime() as " .. the recommend basis for general purpose interval timing"Elis
In fact, developer.android.com/reference/android/os/SystemClock says currentTimeMillis() "should only be used when correspondence with real-world dates and times is important, such as in a calendar or alarm clock application. Interval or elapsed time measurements should use a different clock." Namely, elapsedRealtime().Panlogism
S
9

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

Sw answered 16/2, 2011 at 23:57 Comment(0)
G
1

If you want it in fractional form, just take your value / 10^9 where value is your difference in nanoTime()s.

long nanoSeconds = 500000000;
float seconds = nanoSeconds / 1000000000;

Log.i("NanoTime", nanoSeconds + " ns is the same as " + seconds + " seconds");

Your output would be:

07-27 11:35:47.196: INFO/NanoTime(14237): 500000000 ns is the same as 0.5 seconds
Gradatim answered 27/7, 2011 at 16:38 Comment(1)
times 10^9? that would be extreme large... the code sample is correctGwenngwenneth

© 2022 - 2024 — McMap. All rights reserved.