English 中文(简体)
在爪哇使用纳米时间比较速度性能的方法
原标题:Comparing methods speed performance using nanotime in Java

我想比较下面我所说明的两本《数据方法》(DataMethod)(如果有的话)的速度性能(如果有的话)。

private void readDataMethod1(List<Integer> numbers) {
    final long startTime = System.nanoTime();
    for (int i = 0; i < numbers.size(); i++) {
        numbers.get(i);
    }
    final long endTime = System.nanoTime();
    System.out.println("method 1 : " + (endTime - startTime));
}

private void readDataMethod2(List<Integer> numbers) {
    final long startTime = System.nanoTime();
    int i = numbers.size();
    while (i-- > 0) {
        numbers.get(i);
    }
    final long endTime = System.nanoTime();
    System.out.println("method 2 : " + (endTime - startTime));
}

多数时间,我得到的结果显示 方法2有“更低”的值。

   Run         readDataMethod1    readDataMethod2

     1                  636331             468876
     2                  638256             479269
     3                  637485             515455
     4                  716786             420756

这个测试是否证明读数据方法2比早期快?

最佳回答

这个测试是否证明读数据方法2比早期快?

你走在正确的轨道上,因为你正在“衡量”比较性能,而不是作出假设。

However, there are lots of potential issues to be aware of when writing micro-benchmarks in Java. I would recommend that you read How do I write a correct micro-benchmark in Java?

问题回答

In the first one, you are calling numbers.size() for each iteration. Try storing it in a variable, and check again.

第二个版本运行速度更快的原因是因为您在每次迭代中调用数字. size () 。 以一个数字存储来替换它, 会使其与第一个数字几乎相同 。

这个测试是否证明读数据方法2比早期快?

@aix说,你走对了轨道。然而,你的方法有几个具体问题:

  • 似乎你没有“加入”JVM。 因此可以想象,你的数字可能会被启动效果(JIT编集)扭曲,或者没有一项代码是JIT编集的。

  • 我还争辩说,你的运行太少了。一个 < code> 500000 毫秒, 是 < code>0.0005 秒, 工作不多。 风险在于您应用程序外的“ 其它东西” 可能在测量中引入噪音。 我对运行有更大的信心, 需要数十秒时间。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签