System.currentTimeMillis() work wrong

元气小坏坏 提交于 2019-12-02 06:56:03

问题


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:

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.


回答1:


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;



回答2:


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?



来源:https://stackoverflow.com/questions/13674673/system-currenttimemillis-work-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!