如何通过减去 2 个 nanoTime 对象获得有意义的结果?
我创建了一个监视请求长度的过滤器。
long start = System.nanoTime();
...
long end = System.nanoTime();
现在我怎样才能得到毫秒数?
I created a filter that monitors the length of a request.
long start = System.nanoTime();
...
long end = System.nanoTime();
How can I get the number of milliseconds from this now?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
1 微秒 = 1000 纳秒
1 毫秒 = 1000 微秒
请注意,结果将向下舍入,但您通常无法获得真正的纳秒精度(精度取决于操作系统)。来自
nanoTime()
的 Javadoc:1 microsecond = 1000 nanoseconds
1 millisecond = 1000 microseconds
Note, that the result will be rounded down, but you usually don't get true nanosecond accuracy anyway (accuracy depends on the OS). From the Javadoc on
nanoTime()
:TimeUnit#toMillis(long)(自 Java 5 起)
或
Duration#toMillis() (自 Java 8 起)
或
Duration# Between(Temporal, Temporal)(自 Java 8 起)
或
ChronoUnit.html# Between(Temporal, Temporal)(自 Java 8 起)
TimeUnit#toMillis(long) (since Java 5)
OR
Duration#toMillis() (since Java 8)
OR
Duration#between(Temporal, Temporal) (since Java 8)
OR
ChronoUnit.html#between(Temporal, Temporal) (since Java 8)
另请注意,您可以使用 TimeUnit 类来帮助进行转换。对于旧版本的 Java,以下代码可能是将处理时间转换为其他时间格式的示例:
请注意,新版本的 Java 在 TimeUnit 类中具有快捷方式。
上面的示例会将纳秒长转换为秒。另请注意,这会截断它,因此您确实会损失一些精度。因此,如果切换到分钟,那么您将失去秒的精度。如果你想得到“12分32秒”的结果,那么你就必须用这个解决方案做进一步的处理。
Also note that you can use the TimeUnit class to help with conversion. With older versions of Java, the following code might be an example to transform a processing time into some other time format:
Note that newer versions of Java have shortcuts in the TimeUnit class.
The above sample will turn nanoseconds long into seconds. Also note that this truncates it so you do lose some precision. Therefore, if you switch to minutes then you will lose the precision of seconds. If you want to get a result of "12 minutes and 32 seconds" then you would have to do further processing with this solution.
只需减去它们并将结果除以 10^6 即可。
1 纳秒是 10^-9 秒,相应地,是 10^-6 毫秒。
http://en.wikipedia.org/wiki/Nano-
Just subtract them and divide result by 10^6.
1 nanosecond is 10^-9 seconds and, correspondingly, 10^-6 milliseconds.
http://en.wikipedia.org/wiki/Nano-
您可以使用
System.currentTimeMillis()
。注意事项:
You could just use
System.currentTimeMillis()
.Caveat:
要获得有意义的结果:
To get a meaningful result: