Both seem to be appropriate for timing things on Android. How are they different? Which one is best for timing?
As far as I can tell, there's not really much of a difference, but they use different Linux clocks under the hood.
nanoTime()
uses either clock_gettime()
or gettimeofday()
: see the code here (part of Dalvik VM).
elapsedRealtimeNanos()
used to use clock_gettime()
, but it no longer does. Instead, it now issues an ioctl
to the /dev/alarm
device (see code here), but I'm not exactly sure what the alarm
device driver uses.
I've used elapsedRealtimeNanos()
for a long time with no trouble, but not for any specific reason. Just make sure you realize that neither of these functions will provide the wall clock time.