Java中经过的时间不一致 [英] inconsistent time elapsed in java

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

问题描述

我正在尝试使用nanoTime计算java中经过的时间.但是每次它给我不同的结果.为什么总是不一致?

I am trying to compute time lapsed in java using nanoTime. But everytime it gives me different results. Why it is not consistent always ?

示例代码:

long startTime=System.nanoTime();
String.valueOf(number).length();
long endTime = System.nanoTime();
System.out.println(endTime-startTime);

推荐答案

nanoTime()及其姐妹 currentTimeMillis()并不精确,具体取决于您运行的体系结构您的代码会四舍五入(请参见

nanoTime() and its sister currentTimeMillis() are not exact and depending on the architecture you run your code on they suffer from rounding (see the javadoc for details):

This method provides nanosecond precision, but not necessarily nanosecond resolution 
(that is, how frequently the value changes) -
no guarantees are made except that the resolution is at least as good
as that of currentTimeMillis().

如果您为了确定替代a或b的速度而测量时间,则基本上是在进行微基准测试.有用于此的框架,您应该使用它们. JMH 可能是最著名的Java.如果需要对较大的代码部分执行相同的操作,则可以考虑进行概要分析.

If you measure the time in order to decide if alternative a or b is faster you are basically doing a micro benchmark. There are frameworks for this and you should use them. Probably the one most known for Java is JMH. If you need to do the same for larger code parts you might consider profiling.

您可能想看一下这个stackoverflow帖子:

You might want to have a look at this stackoverflow post: How do I write a correct micro-benchmark in Java?

这篇关于Java中经过的时间不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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