2

How to find the time since Epoch in nanoseconds in Android?

Below APIS are available but they just give the time since boot

  1. SystemClock.elapsedRealtimeNanos() - Time since boot but includes deep sleep time
  2. System.getnano() -> This is up time since boot without the deep sleep time.

For Epoch time, there seems to be only 1 API available.

  • System.currentTimeMillis() -> shows time since Epoch in milliseconds.

Is there a similar API/a new approach to get the time since epoch in nano seconds.

PS : Time since Epoch means, the time elapsed since January 1, 1970 UTC.

Community
  • 1
  • 1
Sandeep
  • 18,356
  • 16
  • 68
  • 108
  • Java does not offer the `clock_gettime` function, so your choice to have more accurate timing is through JNI, also there would be an overhead calling JNI so it would not 100% accurate – Rod_Algonquin Feb 10 '17 at 03:36
  • @Rod_Algonquin Thank you. I see that System.currentTimeMillis() is also a native call. So I guess, it will be kind of ok for me to use JNI, but i was looking for available APIS in android that can give me the nanoseconds.. I guess there are none available as of now. – Sandeep Feb 10 '17 at 03:39
  • @Rod_Algonquin I am trying to look at the native implementation of currentTimeMillis() but unable to find the souce. If you know where is it, please share with me.. It will help me. – Sandeep Feb 10 '17 at 03:41
  • 1
    You can either check it in you local jdk folder the name of the file is `os_solaris.cpp` or you can just go here: http://hg.openjdk.java.net/jdk7u/jdk7u60/hotspot/file/ba66650acf63/src/os/solaris/vm/os_solaris.cpp#l1805 – Rod_Algonquin Feb 10 '17 at 03:48

2 Answers2

1

You can convert the millis to nanos with the TimeUnit class. Try

long nanos = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis());
Jesse Buss
  • 833
  • 6
  • 13
  • This would just convert it. It would not be accurate. I would like to measure the actual time in naoseconds – Sandeep Feb 10 '17 at 03:10
0

Device doesn't have so accurate clock to count nanoseconds when device is off. CPU does, but it counts only from start.

DmitryBorodin
  • 4,584
  • 4
  • 17
  • 29
  • I dont think so. You can get the nano seconds using clock_gettime(CLOCK_REALTIME, &ts) from native code. I verified it from native code. It works fine. I am looking to get a similar value from android application without using JNI/native code.. – Sandeep Feb 10 '17 at 03:18