0

I have the following piece of code to try and determine how long a method call takes to execute:

long start = System.nanoTime();

diag(); // diag() is a native method, called via JNI.

long finish = System.nanoTime();

System.out.println("update() took: " + Long.toString(finish - start));

When being executed on a specific Android device (Xperia P), this diff (finish - start) is 0 most of the time.

What is the reason for this? and is there any better way to try measuring the time this method takes to execute and return?

*Note that other Android devices behave differently

lysergic-acid
  • 19,570
  • 21
  • 109
  • 218
  • 1
    This is a guess, but the `nanoTime` method says that it gives the time "of the most precise timer available"; so most likely it is 0 because the amount of time your method takes is less than the actual resolution of the system timer. – devrobf Jul 23 '13 at 10:41
  • In addition to jazzbassrob's comment, try to run `diag();` multiple times (say 100), and see how long it take: (`(finish-start)/100.0`) – johnchen902 Jul 23 '13 at 10:44

1 Answers1

1

What is the reason for this?

System.nanoTime()'s resolution is device and OS dependent. So if your device's internal clock resolution is too high, System.nanoTime() won't be able to improve things.

is there any better way to try measuring the time this method takes to execute and return?

You can run the method more than once to increase the time spent. But note that benchmarking is a complicated art. You can start with this post: How do I write a correct micro-benchmark in Java? Although it focuses on the hotspot JVM, most principles apply to Dalvik.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783