准确Vs.精确

我想知道的是,我是否应该使用系统。currenttimemillis()或系统。nanotime()时更新我的对象的位置在我的游戏?它们移动的变化与上次通话后经过的时间成正比,我希望尽可能精确。

我读到过不同操作系统之间有一些严重的时间分辨率问题(即Mac / Linux的分辨率几乎是1毫秒,而Windows的分辨率是50毫秒??)我主要在windows上运行我的应用程序,50ms的分辨率似乎非常不准确。

还有比我列出的两个更好的选择吗?

有什么建议/意见吗?


当前回答

旧的jvm中不支持System.nanoTime()。如果这是一个问题,请坚持使用currentTimeMillis

关于准确性,你几乎是正确的。在一些Windows机器上,currentTimeMillis()的分辨率约为10ms(而不是50ms)。我不知道为什么,但是一些Windows机器和Linux机器一样准确。

我过去使用过GAGETimer,取得了一定的成功。

其他回答

旧的jvm中不支持System.nanoTime()。如果这是一个问题,请坚持使用currentTimeMillis

关于准确性,你几乎是正确的。在一些Windows机器上,currentTimeMillis()的分辨率约为10ms(而不是50ms)。我不知道为什么,但是一些Windows机器和Linux机器一样准确。

我过去使用过GAGETimer,取得了一定的成功。

是的,如果需要这样的精度,请使用System.nanoTime(),但请注意,您需要Java 5+ JVM。

在我的XP系统上,我看到系统时间报告为至少100微秒278纳秒,使用以下代码:

private void test() {
    System.out.println("currentTimeMillis: "+System.currentTimeMillis());
    System.out.println("nanoTime         : "+System.nanoTime());
    System.out.println();

    testNano(false);                                                            // to sync with currentTimeMillis() timer tick
    for(int xa=0; xa<10; xa++) {
        testNano(true);
        }
    }

private void testNano(boolean shw) {
    long strMS=System.currentTimeMillis();
    long strNS=System.nanoTime();
    long curMS;
    while((curMS=System.currentTimeMillis()) == strMS) {
        if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)); }
        }
    if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)+", Milli: "+(curMS-strMS)); }
    }

我对纳米时间有丰富的经验。它使用JNI库提供了两个长度的挂钟时间(从纪元开始的秒数和在这一秒内的纳秒)。在Windows和Linux上都可以使用预编译的JNI部分。

system. currenttimemillis()对于运行时间来说是不安全的,因为这个方法对系统的实时时钟变化很敏感。 您应该使用System.nanoTime。 请参阅Java系统帮助:

关于nanoTime方法:

. .这种方法提供纳秒精度,但不一定 纳秒分辨率(即值变化的频率)—不 除了保证分辨率至少和 currentTimeMillis()..

如果你使用System.currentTimeMillis(),你的运行时间可以是负数(返回<-到未来)

如果您只是在寻找极其精确的流逝时间度量,请使用System.nanoTime()。System.currentTimeMillis()将为您提供自epoch以来可能最精确的以毫秒为单位的经过时间,但是System.nanoTime()将为您提供相对于某个任意点的纳秒精确时间。

摘自Java文档:

public static long nanoTime() Returns the current value of the most precise available system timer, in nanoseconds. This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.

例如,要测量一些代码执行所需的时间:

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

更多信息请参见:JavaDoc System.nanoTime()和JavaDoc System.currentTimeMillis()。