使用 System.nanoTime() 时如何确定哪个执行时间更有信誉[重复]

Posted

技术标签:

【中文标题】使用 System.nanoTime() 时如何确定哪个执行时间更有信誉[重复]【英文标题】:How to decide which execution time is more reputable while using System.nanoTime () [duplicate] 【发布时间】:2016-05-26 12:57:29 【问题描述】:

当我尝试在下面测量我的方法的性能执行速度时间时:

  public static int FFMulFast(int firstPol, int secondPol)
  int temp = 0;

  if (firstPol == 0 ||secondPol == 0)

  return 0;

 /*The multiplication is done by using lookup tables. We have used both logarithmic and exponential table for mul
 the idea is firstly look to Logarithmic table then add their powers and find the corresponding of this to exponential table */

   temp = (Log[(firstPol & 0xff)] & 0xff) + (Log[(secondPol & 0xff)] & 0xff);

    if (temp > 255) temp = temp - 255;

    return Exp[(temp & 0xff)];

  

现在当我如下测量这种方法的性能速度时

 public void runABunch() 

    long start = System.nanoTime();
    int a=0x59;
   int b=0xb4;
     for (int i = 0; i < 5000000; i++)
        FFMulFast(a,b);
    long end = System.nanoTime();
    System.out.println("Time in nanoseconda: " + (end-start));
  

这个结果大约是 0.1 秒。

但是,当我运行相同的方法 runABunch 但省略 for 时,我得到完全不同的结果,我不明白为什么这些结果完全不同,哪个更有信誉的是有 for 或没有 for 的那个

public void runABunch() 

long start = System.nanoTime();
int a=0x59;
  int b=0xb4;

    FFMulFast(a,b);
long end = System.nanoTime();
System.out.println("Time in nanoseconda: " + (end-start));

另外,当我放一些 println 语句时,执行时间增加了很多。有人知道为什么吗? 我尝试使用像 java visualvm 这样的分析器,但问题是我看不到任何东西,因为我的应用程序运行完成后它就消失了。

【问题讨论】:

这可能是由 JIT 优化引起的。你在做 JIT 热身吗? 这取决于结果是什么。您是在问为什么在runABunch() 中省略for 循环时系统时间不同? @Deadshot 是的,这就是我所要求的。例如,当我有 for 循环时,这个方法需要 0.01 秒,但是当我在 runABunch 方法中省略 for 时,这个方法需要 0.0003 秒。为什么会有这种差异?这两个中哪一个是最有信誉的? 您没有得到任何与实际性能相关的信息。这只是测量误差。任何可用的基准测试都必须至少花费几秒钟,否则您只测量预热,这与实际程序完全无关。但是还有更多的陷阱,所以请使用 JMH 并阅读链接的帖子。 【参考方案1】:

您不应该尝试像这样手动滚动基准代码。您应该改用 JMH 之类的框架。

【讨论】:

【参考方案2】:

您的问题的答案比您想象的要简单。带有for 循环的代码运行FFMulFast() 方法五百万次,而省略for 循环运行相同的方法,但只运行一次。将同一任务完成五百万次总是会比只运行一次所花费的时间更长。

【讨论】:

以上是关于使用 System.nanoTime() 时如何确定哪个执行时间更有信誉[重复]的主要内容,如果未能解决你的问题,请参考以下文章

统计代码执行时间时,System.currentTimeMillis()与System.nanoTime()哪个更适合?

将 System.currentTimeMillis() 与 System.nanoTime() 结合使用是不是合理?

System.nanoTime与System.currentTimeMillis的区别

System.nanoTime()和System.currentTimeMillis()性能问题

System.currentTimeMillis() 和 System.nanoTime() 哪个更快?别用错了!

System.nanoTime() 的 Java 时代? [复制]