1

I need stopWatch and I used http://www.goldb.org/stopwatchjava.html

It did not work well so I tried write out the value every 1000ms:

stopWatch.start();
HandlerScrollBar.postDelayed(TtScroll,  1000);

private Runnable TtScroll = new Runnable() {
    public void run() {
        long time = stopWatch.getElapsedTime();
        HandlerScrollBar.postDelayed(TtScroll,(long) 1000);
        Log.d(TAG, Long.toString(time));            
    }
};

I can see value of time every second in CatLog and this is result:

enter image description here

Real time is max +5ms but in Column it is at least +3 seconds! How is it possible? It is the same with

new Date().getTime().

Is there some StopWatch class which will pass this test as expected?

Thank you.

vlkpo
  • 199
  • 1
  • 15

2 Answers2

6

If you are measuring elapsed time, and you want it to be correct, you must use System.nanoTime(). You cannot use System.currentTimeMillis(), unless you don't mind your result being wrong.

The purpose of nanoTime is to measure elapsed time, and the purpose of currentTimeMillis is to measure wall-clock time. You can't use the one for the other purpose. The reason is that no computer's clock is perfect; it always drifts and occasionally needs to be corrected.

Since nanoTime's purpose is to measure elapsed time, it is unaffected by any of these small corrections.I would suggest to pick the nanoTime() as it has better accuracy in those microcalculations.

for extremely precise measurements of elapsed time. From its javadoc:

long startTime = System.nanoTime(); 

// ... the code being measured ...

long estimatedTime = System.nanoTime() - startTime;
K_Anas
  • 31,226
  • 9
  • 68
  • 81
  • there were my cumulative fault - you are right. It is working correctly and with System.nanoTime() even more accurately; – vlkpo Dec 02 '12 at 23:13
0

Seems impossible. I've never had System.currentTimeMillis() act that way. Also, you're logging out as Log.d() but the logcat you show indicates a Log.e(). You sure that's the right logcat?

Brian Dupuis
  • 8,136
  • 3
  • 25
  • 29