System.currentTimeMillis的()工作的错误 [英] System.currentTimeMillis() work wrong

查看:374
本文介绍了System.currentTimeMillis的()工作的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要秒表,我用 http://www.goldb.org/stopwatchjava.html

它并不能很好的工作,所以我尝试写出来的值每1000ms的:

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:

实时为max + 5ms的但在柱它至少3秒!这怎么可能?它是同一个以

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?

感谢你。

推荐答案

如果您正在测量经过的时间,你希望它是正确的,你必须使用 System.nanoTime()。不能使用 System.currentTimeMillis的(),除非你不介意你的结果是错误的。

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.

nanoTime 的宗旨,以测量经过时间,和的currentTimeMillis的目的是测量挂钟时间。你不能使用一个用于其他用途。其原因是没有电脑的时钟是完美的;它总是漂移和偶尔需要被校正。

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.

由于nanoTime的目的是测量经过的时间,它不受任何这些小corrections.I会建议挑选nanoTime()因为它在这些microcalculations更高的精度。

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.

极美元经过时刻p $ pcise测量。从它的javadoc:

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

long startTime = System.nanoTime(); 

// ...的code被测量...

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

long estimatedTime = System.nanoTime() - startTime;

这篇关于System.currentTimeMillis的()工作的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆