new Date()
使用System.currentTimeMillis()
这取决于操作系统时钟 - 并且可能随用户更改系统日期和时间而改变。
您应该使用System.nanoTime()
,这具有以下特点:
/**
* Returns the current value of the most precise available system
* timer, in nanoseconds.
*
* <p>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<sup>63</sup>
* nanoseconds) will not accurately compute elapsed time due to
* numerical overflow.
*
* <p> For example, to measure how long some code takes to execute:
* <pre>
* long startTime = System.nanoTime();
* // ... the code being measured ...
* long estimatedTime = System.nanoTime() - startTime;
* </pre>
*
* @return The current value of the system timer, in nanoseconds.
* @since 1.5
*/
public static native long nanoTime();
这不能仅通过更改系统日期进行操作。
完美,谢谢。 – FoppyOmega
任何人都知道iOS SDK的等价物? – Tocco
一个缺点是,当CPU被重置时nanoTime将被重置。这意味着您无法测量手机关机时的精确时间。 – sjkm