0

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

Johan
  • 35,120
  • 54
  • 178
  • 293
  • You can use `System.currentTimeMillis()` http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#currentTimeMillis%28%29 – DNA Jul 03 '12 at 22:19
  • 3
    Did you look through the methods which *are* available on `Date`? `System.nanoTime` is a better approach anyway, or `System.currentTimeMillis()`, but you should have found `Date.getTime()` either way. – Jon Skeet Jul 03 '12 at 22:19
  • Incidentally, for benchmarking, I'd argue that if the different precision of nanoTime and currentTimeMillis matters, then you aren't running the test for long enough! For timing a single operation, nano is more precise. See also http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – DNA Jul 03 '12 at 22:23

3 Answers3

3

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.

CrimsonDiego
  • 3,616
  • 1
  • 23
  • 26
0

What is wrong with System.currentTimeMillis()?

long before = System.currentTimeMillis();
doStuff();
long after = System.currentTimeMillis();
Lucas Arrefelt
  • 3,879
  • 5
  • 41
  • 71
0

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

Darryl Bayliss
  • 2,677
  • 2
  • 19
  • 28