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访问系统时钟的简单/简单方法是什么,以便我可以计算事件的运行时间?
6 个解决方案
#1
77
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()返回“wall-clock”时间,该时间可能会改变(例如:夏令时,管理用户更改时钟),并会影响间隔测量。
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启动)以来的纳秒数,因此不受系统时钟更改的影响。
#2
25
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.");
#3
9
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
#4
6
The Answer by Leigh is correct.
李的回答是正确的。
java.time
Java 8 and later has the java.time framework built in.
Java 8以及以后的Java。建成的时间框架。
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.
瞬间是UTC时间轴上的时刻,具有纳秒分辨率(最高可达9位,小数几分之一秒)。now方法获取当前日期-时间时刻。
Instant now = Instant.now();
2016-03-12T04:29:39.123Z
2016 - 03 - 12 - t04: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.
您可以计算两个瞬时对象之间的运行时间。持续时间使用纳秒分辨率,最大的值为秒,可以保持很长时间。这比目前估计的宇宙年龄要大。
Duration duration = Duration.between( startInstant , stopInstant );
The default output of Duration::toString
is in standard ISO 8601 format. You can also ask for a total count of nanoseconds (toNanos
) or milliseconds (toMillis
), as well as other amounts.
持续时间的默认输出是::toString是标准ISO 8601格式。您还可以要求总数纳秒(toNanos)或毫秒(toMillis),以及其他数量。
Java 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 store nanoseconds 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。时间类可以存储纳秒,它们只能用毫秒来确定当前时刻。这个限制是由于遗留问题(默认的时钟实现使用System.currentTimeMillis()))。
Java 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和以后的版本中,默认的时钟实现可以在高达纳秒的分辨率下确定当前时刻。实际上,这取决于你计算机时钟硬件的精确性。
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:
如果你的目标是基准测试,一定要看看其他的问题,比如:
- How do I write a correct micro-benchmark in Java?
- 如何用Java编写正确的微基准?
- Create quick/reliable benchmark with java?
- 使用java创建快速/可靠的基准?
Frameworks are available to assist with short-duration benchmarking.
可以使用框架来辅助短期基准测试。
#5
5
java.lang.System.currentTimeMillis()
or java.lang.System.nanoTime()
ought to work to measure elapsed time.
nanotime()应该用于度量流逝时间。
#6
3
Here is a small StopWatch class I wrote using the System.nanoTime() as suggested in the answer from Leigh:
下面是我使用System.nanoTime()编写的一个小型秒表类,正如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;
}
#1
77
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()返回“wall-clock”时间,该时间可能会改变(例如:夏令时,管理用户更改时钟),并会影响间隔测量。
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启动)以来的纳秒数,因此不受系统时钟更改的影响。
#2
25
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.");
#3
9
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
#4
6
The Answer by Leigh is correct.
李的回答是正确的。
java.time
Java 8 and later has the java.time framework built in.
Java 8以及以后的Java。建成的时间框架。
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.
瞬间是UTC时间轴上的时刻,具有纳秒分辨率(最高可达9位,小数几分之一秒)。now方法获取当前日期-时间时刻。
Instant now = Instant.now();
2016-03-12T04:29:39.123Z
2016 - 03 - 12 - t04: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.
您可以计算两个瞬时对象之间的运行时间。持续时间使用纳秒分辨率,最大的值为秒,可以保持很长时间。这比目前估计的宇宙年龄要大。
Duration duration = Duration.between( startInstant , stopInstant );
The default output of Duration::toString
is in standard ISO 8601 format. You can also ask for a total count of nanoseconds (toNanos
) or milliseconds (toMillis
), as well as other amounts.
持续时间的默认输出是::toString是标准ISO 8601格式。您还可以要求总数纳秒(toNanos)或毫秒(toMillis),以及其他数量。
Java 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 store nanoseconds 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。时间类可以存储纳秒,它们只能用毫秒来确定当前时刻。这个限制是由于遗留问题(默认的时钟实现使用System.currentTimeMillis()))。
Java 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和以后的版本中,默认的时钟实现可以在高达纳秒的分辨率下确定当前时刻。实际上,这取决于你计算机时钟硬件的精确性。
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:
如果你的目标是基准测试,一定要看看其他的问题,比如:
- How do I write a correct micro-benchmark in Java?
- 如何用Java编写正确的微基准?
- Create quick/reliable benchmark with java?
- 使用java创建快速/可靠的基准?
Frameworks are available to assist with short-duration benchmarking.
可以使用框架来辅助短期基准测试。
#5
5
java.lang.System.currentTimeMillis()
or java.lang.System.nanoTime()
ought to work to measure elapsed time.
nanotime()应该用于度量流逝时间。
#6
3
Here is a small StopWatch class I wrote using the System.nanoTime() as suggested in the answer from Leigh:
下面是我使用System.nanoTime()编写的一个小型秒表类,正如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;
}