Java中的System.nanoTime()为相同的输入提供不同的运行时间

iam*_*rem 0 java

我使用以下代码来测量程序的运行时间,

码:

public static void main(String[] args) {
    String a = "agtacgtcatacgtctagtactacgttca";
    String b = "gtatccctagactsgtatcatacgtctat";
    long startTime = System.nanoTime();
    //This method call computes the Longest Common Sequence of the given 2 strings.
    System.out.println(LCS.Linear.computeLCS(a, b));
    long endTime = System.nanoTime();
    System.out.println("Took "+(endTime - startTime) + " ns");
}
Run Code Online (Sandbox Code Playgroud)

相同输入的样本输出:

运行1:

gtacctagctgtactacgtta
Took 1971471 ns
Run Code Online (Sandbox Code Playgroud)

运行2:

gtacctagctgtactacgtta
Took 2242336 ns
Run Code Online (Sandbox Code Playgroud)

为什么每次都有不同的运行时间?

如何查找该方法调用的实际运行时间?

aio*_*obe 9

那些运行时间的大小是2毫秒!对于两次单独的运行,您不能指望它们是相同的.从文档:

该方法提供纳秒精度,但不一定是纳秒精度.

像这样的微基准测试非常难以获得准确的数据.你有几个不确定性的来源:

  • 您计算机上的其他进程
  • JVM热身
  • JIT编译
  • 垃圾收集

仅举几例.您应该至少尝试运行算法10.000次左右并取平均值.

进一步阅读: