views:

50

answers:

2

How do I keep track of the runtime of an application.

A: 

You could try to get the current time when you first start the app, and then when you want to know how long the app has run for just get the current time again and then subtract the two to get the difference.

// store this as a global variable when you start the app
long start = System.currentTimeMillis();

...

// run this method when you want to query how long the app has run for
public long getTimeInMillisecondsAppHasRun()
{
    long current = System.currentTimeMillis();
    return current - start;
}
Ben Holland
Actually this may not be the best method. If the system time is changed these measurements will be effected. See http://developer.android.com/reference/java/lang/System.html#currentTimeMillis%28%29 for more details.
Ben Holland
+2  A: 

What do you mean by runtime? The time elapsed after you launch an application?

I don't think there is any direct method that can give you the elapsed time. You can maintain a timer on you own.

You can also use System.nanoTime() to get the most accurate timing.

long startTime = System.nanoTime();    
// ... the code being measured ...    
long estimatedTime = System.nanoTime() - startTime;

Edit---

Yes i think Ben is correct.. If you want to just measure how long a process is running then you can try using this approach android.os.Process.getElapsedCpuTime() - This should return the elapsed milliseconds your process has run. I believe your application also should run on a unique process ID. So that time should be fine

Rahul
+1 for elapsed. That's good advise.
mrrtnn
Found this one interesting: http://developer.android.com/reference/android/os/SystemClock.html#elapsedRealtime%28%29
mrrtnn