Search code examples
javaandroidblockingnonblocking

Quickiest/easiest way to find methods in Java/Android that take a second or more to execute


I am trying to figure out which methods (esp on the Main Thread) take more than a second to execute. Unfortunately I am using DDMS and traceview, but i don't really understand how to read the data provided. Is there an easy way to find long running methods?


Solution

  • For a tutorial on how to use traceview:

    traceview

    Remember that network or db calls can take long time and should not be called on main thread, use a background thread or AsyncTask to complete those calls.

    Other than this you could probably roll your own time measuring helper method something like this (this is utilizing reflection and returns the method invocation time in milliseconds):

    public static long timeMethod(Method m, Object obj, Object... args) {
        long start = 0, stop = 0;
        try {
            start = SystemClock.uptimeMillis();
            m.invoke(obj, args);
            stop = SystemClock.uptimeMillis();
        } catch (Exception e) {
            return ERROR;
        }
        return stop - start;
    }
    

    (Error is just -1, this happens if the method with specified args aren't found etc)