Question

I would like to see how long it takes for a certain method to execute in my android app. My first idea was to do something like this:

Date date1 = new Date();

doStuff();

Date date2 = new Date();

//compare date difference in ms

But for starters, date objects doesnt seem to have a .getMilliseconds(), and thats what im after. Is there any easier and / or better way to solve this?

Thanks

Was it helpful?

Solution

You'll probably want to use System.nanoTime() to do your time counting, as it uses the highest-precision timer available. Another thing to do when testing code efficiency is to not just run it once, but to run it repeatedly, and take the average time as your estimate. This gives better results in the long run, as CPU usage can spike if some other program is also trying to run.

OTHER TIPS

What is wrong with System.currentTimeMillis()?

long before = System.currentTimeMillis();
doStuff();
long after = System.currentTimeMillis();

You could use the Android profiling tools, which can do this kind of stuff in a nice graphical view as the app is running in the emulator.

More info here: http://developer.android.com/tools/debugging/debugging-tracing.html

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