java中的毫秒计时

发布于 2024-09-11 18:21:16 字数 177 浏览 0 评论 0原文

我在 Java 应用程序中对各种事务进行计时。在事务开始时,我通过实例化日历来获取开始时间,然后获取小时、分钟、秒和毫秒。我完成事务,实例化一个新的日历并获得新的小时、分钟、秒和毫秒。我的推理是开始时间和结束时间之间的差异就是事务的时间。这似乎在大多数情况下都有效,但在极少数情况下,结束时间早于开始时间。为什么会发生这种情况以及如何预防?

I time various transactions in my Java application. At the start of the transaction, I get a start time by instantiating a Calendar and then getting the hour, minute, second, and millisecond. I complete the transaction, instantiate a new Calendar and get a new hour, minute, second, and millisecond. My reasoning is that the difference between the start time and the end time is the time of the transaction. This seems to work most of the time, but a tiny fraction of the time, the end time is earlier than the start time. Why would this occur and how can I prevent it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧时浪漫 2024-09-18 18:21:16

好吧,一方面,一种更简单的计算差异的方法是使用诸如 System.currentTimeMillis() 或 System.nanoTime() 之类的东西 - 这样你就不会除了简单的减法之外,还需要做任何事情来获取开始和结束之间的毫秒数或纳秒数。

但是,如果您的系统时钟由 NTP 或类似的东西更新,那么时间可能会偶尔倒退 - 取决于时钟偏差的处理方式。 (有些系统只是减慢系统时钟一段时间,使其回到现实;其他系统可能会出现不连续性。)

我不确定避免这种情况的最佳方法 - 我不相信相信 JRE 目前具有与 .NET 中的 Stopwatch 等效的功能,它纯粹用于测量间隔,并且(我相信)不会因系统时钟变化而混乱。

(我同意埃里克的Joda Time的推荐,顺便说一句 - 尽管我认为你不需要它这个特殊问题。)

Well, for one thing a simpler way of computing the difference would be to use something like System.currentTimeMillis() or System.nanoTime() - that way you don't need to do anything other than just a simple subtraction to get the number of milliseconds or the number of nanoseconds between the start and the end.

However, if your system clock is being updated by NTP or something similar, then time may effectively go backwards occasionally - depending on how clock skew is handled. (Some systems just slow down the system clock for a while to skew it back to reality; others may have discontinuities.)

I'm not sure of the best way of avoiding this - I don't believe the JRE currently has anything equivalent to Stopwatch in .NET, which is purely for measuring intervals and doesn't (I believe) get messed up by the system clock changing.

(I go along with Erick's recommendation of Joda Time, btw - although I don't think you need it for this particular problem.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文