Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top