Measuring performance in the Android SDK

Michael A. Jackson once stated “The First Rule of Program Optimization: Don’t do it. The Second Rule of Program Optimization (for experts only!): Don’t do it yet.”

Of course we needed to measure execution times before jumping to action and spending valuable time on performance optimization. We found the android.util.TimingLogger helper class from the Android SDK very helpful so here comes a short description on how to use it:

Whithin the method or class in question create an TimingLogger object, execute some code and dump the statistics to the android log.

TimingLogger timings = new TimingLogger("TopicLogTag",
"preparePicturesFromList");
// ... your time consuming code
timings.dumpToLog();

Note that the output will only be dumped to the log if you set the VERBOSE log level for the given log tag (here named “TopicLogTag”):

 $ adb shell setprop log.tag.TopicLogTag VERBOSE

now start your Activity and make sure the code you want to measure is executed

 $ adb logcat -v time TopicLogTag:V *:E
...
D/TopicLogTag(14857): preparePicturesFromList: begin
D/TopicLogTag(14857): preparePicturesFromList: end, 2711 ms

For more informations about log levels and filtering the log output see the Andorid documentation about debugging, the Log reference and especialy the isLoggable() method.

If the informations you get from this measurements is to coarse you can split the timings into sub-tasks with the addSplit(“split label”) method:

TimingLogger timings = new TimingLogger("TopicLogTag", "preparePicturesFromList");
// ... time consuming code which creates picture objects
timings.addSplit("creating picture objects");
// ... time consuming code which generates thumbnails
timings.addSplit("generating thumbnails");
timings.dumpToLog();

The log output will then look like

 $ adb logcat -v time TopicLogTag:V *:E
D/TopicLogTag(14857): preparePicturesFromList: begin
D/TopicLogTag(14857): preparePicturesFromList:      1999 ms, creating
picture objects
D/TopicLogTag(14857): preparePicturesFromList:      712 ms, generating
thumbnails
D/TopicLogTag(14857): preparePicturesFromList: end, 2711 ms