本文介绍了System.currentTimeMillis vs System.nanoTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道的是我是否应该使用 System.currentTimeMillis() System.nanoTime ()在我的游戏中更新对象的位置时?它们的运动变化与自上次通话后经过的时间成正比,我希望尽可能精确。

What I would like to know is whether I should use System.currentTimeMillis() or System.nanoTime() when updating my object's positions in my game? Their change in movement is directly proportional to the elapsed time since the last call and I want to be as precise as possible.

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

I've read that there are some serious time-resolution issues between different operating systems (namely that Mac / Linux have an almost 1 ms resolution while Windows has a 50ms resolution??). I'm primarly running my apps on windows and 50ms resolution seems pretty inaccurate.

有没有比我列出的两个更好的选项?

Are there better options than the two I listed?

有任何建议/意见吗?

推荐答案

如果您只是想要非常精确地测量已用时间,请使用 System.nanoTime() System.currentTimeMillis()将为您提供自纪元以来最精确的经过时间(以毫秒为单位),但 System.nanoTime()相对于某个任意点给出一个纳秒精确的时间。

If you're just looking for extremely precise measurements of elapsed time, use System.nanoTime(). System.currentTimeMillis() will give you the most accurate possible elapsed time in milliseconds since the epoch, but System.nanoTime() gives you a nanosecond-precise time, relative to some arbitrary point.

来自Java文档:

public static long nanoTime()

返回最精确的可用系统计时器的当前值,以纳秒为单位。

Returns the current value of the most precise available system timer, in nanoseconds.

此方法只能用于
测量经过时间而不是
与系统
或挂钟时间的任何其他概念有关。返回的值
表示纳秒,因为某些
固定但是任意时间(未来可能在
,因此值可能是
为负)。这种方法提供
纳秒的精度,但不是
必然是纳秒精度。关于
频繁值变化的方式,没有
保证。连续调用中的差异
跨越大于
而不是大约292年(2
纳秒)将无法准确地计算
由于数字$ b而导致的经过时间$ b溢出。

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 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 (2 nanoseconds) will not accurately compute elapsed time due to numerical overflow.

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

For example, to measure how long some code takes to execute:

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

参见:和了解更多信息。

See also: JavaDoc System.nanoTime() and JavaDoc System.currentTimeMillis() for more info.

这篇关于System.currentTimeMillis vs System.nanoTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 19:00