Java 计算程序运行时间
使用 System.NanoTime()
1 public static long nanoTime()Returns the current value of the running Java Virtual Machine’s high-resolution time source, 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). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.
This method provides nanosecond precision, but not necessarily nanosecond resolution (that is, how frequently the value changes) - no guarantees are made except that the resolution is at least as good as that of
currentTimeMillis()
.Differences in successive calls that span greater than approximately 292 years ($2^{63}$ nanoseconds) will not correctly compute elapsed time due to numerical overflow.
The values returned by this method become meaningful only when the difference between two such values, obtained within the same instance of a Java virtual machine, is computed.
For example, to measure how long some code takes to execute:
1
2
3 long startTime = System.nanoTime();
// ... the code being measured ...
long estimatedTime = System.nanoTime() - startTime;To compare two nanoTime values
1
2
3 long t0 = System.nanoTime();
...
long t1 = System.nanoTime();one should use
t1 - t0 < 0
, nott1 < t0
, because of the possibility of numerical overflow.
- Returns:
the current value of the running Java Virtual Machine’s high-resolution time source, in nanoseconds
- Since:
1.5
示例
1 | long startTime; |
使用 System.currentTimeMillis()
1 public static long currentTimeMillis()Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
See the description of the class
Date
for a discussion of slight discrepancies that may arise between “computer time” and coordinated universal time (UTC).
Returns:
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
See Also:
示例
1 | long startTime = System.currentTimeMillis(); |
可能的误差
System.currentTimeMillis()
在部分 Windows 系统中可能存在 10ms 的误差。有人说在他的游戏程序中使用 nanoTime()
之后比使用 currentTimeMillis()
的时候游戏画面过渡更平滑。