在Java中测量开销的时间 [英] Time measuring overhead in Java

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

问题描述

当测量低级别的经过时间时,我可以选择使用以下任何一种:

When measuring elapsed time on a low level, I have the choice of using any of these:

System.currentTimeMillis();
System.nanoTime();

两种方法都是实现的 native 。在深入研究任何C代码之前,有没有人知道是否有任何实质性的开销要求调用其中一个?我的意思是,如果我真的不关心额外的精度,那么预期哪个CPU耗时更少?

Both methods are implemented native. Before digging into any C code, does anyone know if there is any substantial overhead calling one or the other? I mean, if I don't really care about the extra precision, which one would be expected to be less CPU time consuming?

注意:我正在使用标准Java 1.6 JDK,但问题可能适用于任何JRE ......

N.B: I'm using the standard Java 1.6 JDK, but the question may be valid for any JRE...

推荐答案

此页面上标记正确的答案实际上是不正确。由于JVM死代码消除(DCE),堆栈替换(OSR),循环展开等,这不是编写基准测试的有效方法。只有像Oracle的JMH微基准测试框架这样的框架才能正确地测量这样的东西。如果您对有效性有任何疑问,请阅读这篇文章这些微基准测试。

The answer marked correct on this page is actually not correct. That is not a valid way to write a benchmark because of JVM dead code elimination (DCE), on-stack replacement (OSR), loop unrolling, etc. Only a framework like Oracle's JMH micro-benchmarking framework can measure something like that properly. Read this post if you have any doubts about the validity of such micro benchmarks.

这是的一个JMH基准测试System.currentTimeMillis() vs System.nanoTime()

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@State(Scope.Benchmark)
public class NanoBench {
   @Benchmark
   public long currentTimeMillis() {
      return System.currentTimeMillis();
   }

   @Benchmark
   public long nanoTime() {
    return System.nanoTime();
   }
}

以下是结果(在英特尔酷睿i5上) ):

And here are the results (on an Intel Core i5):

Benchmark                            Mode  Samples      Mean   Mean err    Units
c.z.h.b.NanoBench.currentTimeMillis  avgt       16   122.976      1.748    ns/op
c.z.h.b.NanoBench.nanoTime           avgt       16   117.948      3.075    ns/op

其中显示 System.nanoTime()稍微快一些,每次调用~118ns,相比之下~~ 123ns。然而,同样清楚的是,一旦考虑到平均误差,两者之间几乎没有差别。结果也可能因操作系统而异。但一般的理由应该是它们在开销方面基本相同。

Which shows that System.nanoTime() is slightly faster at ~118ns per invocation compared to ~123ns. However, it is also clear that once the mean error is taken into account, there is very little difference between the two. The results are also likely to vary by operating system. But the general takeaway should be that they are essentially equivalent in terms of overhead.

UPDATE 2015/08/25:虽然这个答案更接近正确,但使用JMH测量,它仍然是不正确的。测量类似 System.nanoTime()本身就是一种特殊的扭曲基准测试。答案和权威性文章是这里

UPDATE 2015/08/25: While this answer is closer to correct that most, using JMH to measure, it is still not correct. Measuring something like System.nanoTime() itself is a special kind of twisted benchmarking. The answer and definitive article is here.

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

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