nanoTime()

canalrun

Well-Known Member
Licensed User
Longtime User
Hello all,
I need to do some high resolution timing. Milliseconds resolution is not enough, I need microseconds or nanoseconds.

I found the Android Java routine:
java.lang.System
nanoTime()

This would be great for measuring elapsed time.

I am using the Reflector library to access this function - essentially using the Reflector method:
curtm = refl.RunStaticMethod("java.lang.System", "nanoTime", Null, Null)

In the Reflector docs, I see mention of the word "inefficient". Is this a good way to access the nanoTime() function from B4A? I think I may be encountering a lot of overhead with this function call.

Is there a better way with or without using the Reflector library?

I need timing resolution of this order - microseconds or nanoseconds.

Thanks,
Barry.
 

agraham

Expert
Licensed User
Longtime User
You won't get micro or nanosecond accurate timing in a multi-threaded OS like Android. Even accurate millisecond resolution timing is not possible as you are liable to be timesliced at any time without any indication that it has happened. You really need dedicated hardware to do accurate elapsed time measurement.
 
Upvote 0

canalrun

Well-Known Member
Licensed User
Longtime User
Thanks for the reply.

I totally agree, but this is what I have to work with. The timing is used for code profiling not real-time measurement or control.

The interval over which I'm looking is in the hundreds of microseconds range. Most of the time it works. For those times I get an inaccurate measurement, oh well.

With those realizations in mind, I am looking for the best way to acquire timing through Android's highest resolution time source, nanoTime().

Barry.
 
Upvote 0

JesseW

Active Member
Licensed User
Longtime User
Andrew, in the Wiki, Erel says nothing is allowed to interrupt Activity_Pause. Could Barry access this nanoTime thing in Activity_Pause, triggered bu an Activity.Finish and write his findings to a file for use on the Apps next run?
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
Erel says nothing is allowed to interrupt Activity_Pause.
That's an over-interpretation of what he says. The debugger will not stop in Activity_Pause, however I can see no reason why the system would not do a task switch during it as there is no special protection that I can see. It could be away for many milliseconds but any way that's not appropriate for what he wants to do.

Most of the time it works. For those times I get an inaccurate measurement, oh well ... looking for the best way
The only way is the Reflection way. The method call overhead should be fairly constant and you could gauge it by timing two successive calls and then approximately compensate by adjusting your actual readings by that value.

Have you looked into Profiling with Traceview and dmtracedump | Android Developers
 
Upvote 0
Top