java中的毫秒计时
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,一方面,一种更简单的计算差异的方法是使用诸如 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()
orSystem.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.)