如何在 Java 中测量经过的时间?
我想要这样的东西:
public class Stream
{
public startTime;
public endTime;
public getDuration()
{
return startTime - endTime;
}
}
同样重要的是,例如,如果 startTime 是 23:00,endTime 是 1:00,则持续时间为 2:00.
Also it is important that for example if the startTime it's 23:00 and endTime 1:00 to get a duration of 2:00.
在 Java 中使用哪些类型来完成此任务?
Which types to use in order to accomplish this in Java?
推荐答案
很遗憾,到目前为止发布的十个答案都不是完全正确的.
Unfortunately, none of the ten answers posted so far are quite right.
如果您要测量经过的时间,并且希望它正确,则必须使用System.nanoTime()
.你不能使用 System.currentTimeMillis()
,除非你不介意你的结果是错误的.
If you are measuring elapsed time, and you want it to be correct, you must use System.nanoTime()
. You cannot use System.currentTimeMillis()
, unless you don't mind your result being wrong.
nanoTime
的目的是测量经过时间,currentTimeMillis
的目的是测量wall-clock时间>时间.您不能将其中一个用于其他目的.原因是没有计算机的时钟是完美的.它总是漂移,偶尔需要纠正.这种更正可能是手动进行的,或者在大多数机器的情况下,有一个进程正在运行并不断地对系统时钟(挂钟")进行小幅更正.这些往往会经常发生.每当有闰秒时,就会发生另一种这样的修正.
The purpose of nanoTime
is to measure elapsed time, and the purpose of currentTimeMillis
is to measure wall-clock time. You can't use the one for the other purpose. The reason is that no computer's clock is perfect; it always drifts and occasionally needs to be corrected. This correction might either happen manually, or in the case of most machines, there's a process that runs and continually issues small corrections to the system clock ("wall clock"). These tend to happen often. Another such correction happens whenever there is a leap second.
由于 nanoTime
的目的是测量经过的时间,因此不受任何这些小修正的影响.这是你想要使用的.当前使用 currentTimeMillis
进行的任何计时都将关闭——甚至可能是负数.
Since nanoTime
's purpose is to measure elapsed time, it is unaffected by any of these small corrections. It is what you want to use. Any timings currently underway with currentTimeMillis
will be off -- possibly even negative.
您可能会说,这听起来好像并没有那么重要,"我说,也许不是,但总的来说,正确的代码不是比错误的代码更好吗?此外,nanoTime
无论如何都更短.
You may say, "this doesn't sound like it would ever really matter that much," to which I say, maybe not, but overall, isn't correct code just better than incorrect code? Besides, nanoTime
is shorter to type anyway.
之前发布的关于 nanoTime
通常只有微秒精度的免责声明是有效的.此外,调用可能需要超过一微秒的时间,具体取决于情况(其他情况也是如此),因此不要期望正确地计时非常非常小的时间间隔.
Previously posted disclaimers about nanoTime
usually having only microsecond precision are valid. Also it can take more than a whole microsecond to invoke, depending on circumstances (as can the other one), so don't expect to time very very small intervals correctly.
相关文章