What is best method to measure execution time of Android code snippet?
I have a section of code before and after which I want to place timestamps to find out it\'s e
What about TimingLogger?
From TimingLogger documentation:
TimingLogger timings = new TimingLogger(YOUR_TAG, "methodA");
// ... do some work A ...
timings.addSplit("work A");
// ... do some work B ...
timings.addSplit("work B");
// ... do some work C ...
timings.addSplit("work C");
timings.dumpToLog();
and the dump will look like:
D/TAG (3459): methodA: begin
D/TAG (3459): methodA: 9 ms, work A
D/TAG (3459): methodA: 1 ms, work B
D/TAG (3459): methodA: 6 ms, work C
D/TAG (3459): methodA: end, 16 ms
Do not forget to enable your tag by running: adb shell setprop log.tag.YOUR_TAG VERBOSE
Kotlin Developers
To get the elapsed time in MilliSeconds:
val elapsedTime= measureTimeMillis {
// call you method from here or add any other statements
}
To get the time in NanoSeconds:
val elapsedTime= measureNanoTime {
// call you method from here or add any other statements
}
What would be the best way to measure execution time
System.nanoTime()
is probably a good choice. Jake Wharton is using that with Hugo, for example.
and get good precision
This is not strictly possible, as anything can happen on the device while your method is executing. Those external factors will affect your time measurements, by stealing away CPU time, tying up I/O channels, etc. You need to average your tests across several runs to try to average out those external factors, and accuracy/precision will suffer as a result.
And, as Marcin Orlowski notes, to actually figure out why you are consuming certain amounts of time, use Traceview.
What you ask about is called profiling, and there're tools to help you with that on Android as well. See article Profiling with Traceview and dmtracedump on official developer site.
I usually use System.nanoTime()
for quick Measurement.
A simple Setup like this
val startTime = System.nanoTime()
//DO SOMETHING
Log.e("Measure", TASK took : " + ((System.nanoTime()-startTime)/1000000)+ "mS\n")