如何衡量Java中的时间? [英] How do I measure time elapsed in Java?

查看:114
本文介绍了如何衡量Java中的时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要这样的东西:

public class Stream
{
    public startTime;
    public endTime;

    public getDuration()
    {
        return startTime - endTime;
    }
}

同样重要的是,例如如果startTime它是23:00和结束时间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 的目的是衡量挂钟时间。你不能将它用于其他目的。原因是没有计算机的时钟是完美的;它总是漂移,偶尔需要纠正。这种修正可能是手动发生的,或者在大多数机器的情况下,有一个过程运行并不断对系统时钟(挂钟)进行小的修正。这些往往经常发生。只要有闰秒,就会发生另一次这样的修正。

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.

这篇关于如何衡量Java中的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆