How to measure elapsed time
Even better!
long tStart = System.nanoTime();
long tEnd = System.nanoTime();
long tRes = tEnd - tStart; // time in nanoseconds
Read the documentation about nanoTime()!
Per the Android docs SystemClock.elapsedRealtime()
is the recommend basis for general purpose interval timing. This is because, per the documentation, elapsedRealtime() is guaranteed to be monotonic, [...], so is the recommend basis for general purpose interval timing.
The SystemClock documentation has a nice overview of the various time methods and the applicable use cases for them.
SystemClock.elapsedRealtime()
andSystemClock.elapsedRealtimeNanos()
are the best bet for calculating general purpose elapsed time.SystemClock.uptimeMillis()
andSystem.nanoTime()
are another possibility, but unlike the recommended methods, they don't include time in deep sleep. If this is your desired behavior then they are fine to use. Otherwise stick withelapsedRealtime()
.- Stay away from
System.currentTimeMillis()
as this will return "wall" clock time. Which is unsuitable for calculating elapsed time as the wall clock time may jump forward or backwards. Many things like NTP clients can cause wall clock time to jump and skew. This will cause elapsed time calculations based oncurrentTimeMillis()
to not always be accurate.
When the game starts:
long startTime = SystemClock.elapsedRealtime();
When the game ends:
long endTime = SystemClock.elapsedRealtime();
long elapsedMilliSeconds = endTime - startTime;
double elapsedSeconds = elapsedMilliSeconds / 1000.0;
Also, Timer() is a best effort timer and will not always be accurate. So there will be an accumulation of timing errors over the duration of the game. To more accurately display interim time, use periodic checks to System.currentTimeMillis()
as the basis of the time sent to setText(...)
.
Also, instead of using Timer
, you might want to look into using TimerTask
, this class is designed for what you want to do. The only problem is that it counts down instead of up, but that can be solved with simple subtraction.
When the game starts:
long tStart = System.currentTimeMillis();
When the game ends:
long tEnd = System.currentTimeMillis();
long tDelta = tEnd - tStart;
double elapsedSeconds = tDelta / 1000.0;