如何计算java中事件的经过时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/238920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I calculate the elapsed time of an event in java?
提问by kafuchau
What's a simple/easy way to access the system clock using Java, so that I can calculate the elapsed time of an event?
使用 Java 访问系统时钟的简单/简便方法是什么,以便我可以计算事件的经过时间?
采纳答案by Leigh
I would avoid using System.currentTimeMillis()
for measuring elapsed time. currentTimeMillis()
returns the 'wall-clock' time, which may change (eg: daylight savings, admin user changing the clock) and skew your interval measurements.
我会避免使用System.currentTimeMillis()
来测量经过的时间。currentTimeMillis()
返回“挂钟”时间,该时间可能会发生变化(例如:夏令时、管理员用户更改时钟)并扭曲您的间隔测量。
System.nanoTime()
, on the other hand, returns the number of nanoseconds since 'some reference point' (eg, JVM start up), and would therefore not be susceptible to system clock changes.
System.nanoTime()
,另一方面,返回自“某个参考点”(例如,JVM 启动)以来的纳秒数,因此不会受到系统时钟变化的影响。
回答by tvanfosson
java.lang.System.currentTimeMillis()
or java.lang.System.nanoTime()
ought to work to measure elapsed time.
java.lang.System.currentTimeMillis()
或java.lang.System.nanoTime()
应该工作以测量经过的时间。
回答by jjnguy
This is some sample code.
这是一些示例代码。
long startTime = System.currentTimeMillis();
// Run some code;
long stopTime = System.currentTimeMillis();
System.out.println("Elapsed time was " + (stopTime - startTime) + " miliseconds.");
回答by Spencer Kormos
Apache Commons-Lang also has the StopWatch class suited just for your purpose. It uses System.currentTimeMillis(), so you'll still have resolution problems, but you can pause and do lap times and such. I use it as standard now for event stats.
Apache Commons-Lang 也有适合您用途的 StopWatch 类。它使用 System.currentTimeMillis(),因此您仍然会遇到分辨率问题,但您可以暂停并进行圈速等。我现在使用它作为事件统计的标准。
http://commons.apache.org/lang/api-release/org/apache/commons/lang/time/StopWatch.html
http://commons.apache.org/lang/api-release/org/apache/commons/lang/time/StopWatch.html
回答by Wilhem Meignan
Here is a small StopWatch class I wrote using the System.nanoTime() as suggested in the answer from Leigh:
这是我使用 System.nanoTime() 编写的一个小型 StopWatch 类,如 Leigh 的回答中所建议:
public class StopWatch {
// Constructor
public StopWatch() {
}
// Public API
public void start() {
if (!_isRunning) {
_startTime = System.nanoTime();
_isRunning = true;
}
}
public void stop() {
if (_isRunning) {
_elapsedTime += System.nanoTime() - _startTime;
_isRunning = false;
}
}
public void reset() {
_elapsedTime = 0;
if (_isRunning) {
_startTime = System.nanoTime();
}
}
public boolean isRunning() {
return _isRunning;
}
public long getElapsedTimeNanos() {
if (_isRunning) {
return System.nanoTime() - _startTime;
}
return _elapsedTime;
}
public long getElapsedTimeMillis() {
return getElapsedTimeNanos() / 1000000L;
}
// Private Members
private boolean _isRunning = false;
private long _startTime = 0;
private long _elapsedTime = 0;
}
回答by Basil Bourque
The Answer by Leighis correct.
java.time
时间
Java 8 and later has the java.time framework built in.
Java 8 及更高版本内置了 java.time 框架。
An Instant
is a moment on the timeline in UTC with nanosecond resolution (up to 9 digits of a decimal fraction of a second). The now
method grabs the current date-time moment.
AnInstant
是 UTC 时间线上的一个时刻,具有纳秒分辨率(最多 9 位秒的十进制小数)。该now
方法获取当前日期时间时刻。
Instant now = Instant.now();
2016-03-12T04:29:39.123Z
2016-03-12T04:29:39.123Z
You can calculate the elapsed time between a pair of Instant
objects as a Duration
. The duration uses nanosecond resolution with a maximum value of the seconds that can be held in a long. This is greater than the current estimated age of the universe.
您可以将一对Instant
对象之间经过的时间计算为Duration
. 持续时间使用纳秒分辨率,最大值是可以保持的秒数。这比目前估计的宇宙年龄还要大。
Duration duration = Duration.between( startInstant , stopInstant );
The default output of Duration::toString
is in standard ISO 8601format. You can also ask for a total count of nanoseconds (toNanos
) or milliseconds (toMillis
), as well as other amounts.
的默认输出采用Duration::toString
标准ISO 8601格式。您还可以要求纳秒 ( toNanos
) 或毫秒 ( toMillis
)的总计数,以及其他数量。
Java 8
爪哇 8
In Java 8, fetching the current moment resolves only to millisecond resolution (up to 3 digits of a decimal fraction of a second). So while the java.time classes can storenanoseconds they can only determine the current moment with milliseconds. This limitation is due to a legacy issue (the default Clock
implementation uses System.currentTimeMillis()
).
在 Java 8 中,获取当前时刻仅解析为毫秒分辨率(最多 3 位小数秒)。因此,虽然 java.time 类可以存储纳秒,但它们只能以毫秒为单位确定当前时刻。此限制是由于遗留问题(默认Clock
实现使用System.currentTimeMillis()
)。
Java 9
爪哇 9
In Java 9 and later, the default Clock
implementation can determine the current moment in up to nanosecond resolution. Actually doing so depends on the fineness of your computer's clock hardware.
在 Java 9 及更高版本中,默认Clock
实现可以以高达纳秒的分辨率确定当前时刻。实际上这样做取决于计算机时钟硬件的精细程度。
See this OpenJDK issue page for more info: Increase the precision of the implementation of java.time.Clock.systemUTC()
有关更多信息,请参阅此 OpenJDK 问题页面:提高 java.time.Clock.systemUTC() 的实现精度
Micro Benchmark
微基准
If your purpose is benchmarking, be sure to look at other Questions such as:
如果您的目的是进行基准测试,请务必查看其他问题,例如:
Frameworks are available to assist with short-duration benchmarking.
框架可用于协助进行短期基准测试。