【问题标题】:getting execution time using getCurrentThreadUserTime()使用 getCurrentThread UserName() 获取执行时间
【发布时间】:2014-10-07 19:48:17
【问题描述】:

我正在尝试测量一个循环的执行时间,这是一个简单的添加矩阵。 这是我的代码:

        //get integers m and n from user before this.
        long start,end,time;
        int[][] a = new int[m][n];
        int[][] b = new int[m][n];
        int[][] c= new int[m][n];

        start = getUserTime();

        for(int i = 0;i < m;i++)
        {
            for(int j = 0;j < n;j++)
            {
                c[i][j] = a[i][j]+b[i][j];
            }
        }
        end = getUserTime();

        time = end - start;


       /** Get user time in nanoseconds. */
       public long getUserTime() {
            ThreadMXBean bean = ManagementFactory.getThreadMXBean( );
            return bean.isCurrentThreadCpuTimeSupported( ) ?
            bean.getCurrentThreadUserTime() : 0L;
       }

问题是,有时它会返回 0,例如当我输入 1000 作为 m 和 n 时。这意味着我要添加两个 1000x1000 矩阵。有时它返回 0,有时返回 15ms(都不断重复)。

我不知道该相信 15ms 还是 0。它们之间有很大的不同。 我知道精度取决于操作系统,并不是真正的纳秒精度,但 15 毫秒是一个精度问题。

编辑:这段代码的目的是测量循环中的 CPU 性能。所以如果可能的话,我希望编译器优化和操作系统上下文切换等的影响最小。

非常感谢。

【问题讨论】:

标签: java execution-time


【解决方案1】:

您应该使用System.nanoTime()。 (API Here)

来自文档:

此方法只能用于测量经过的时间,不能用于 与系统或挂钟时间的任何其他概念有关。价值 返回代表纳秒,因为一些固定但任意的来源 时间(也许在将来,所以值可能是负数)。相同 在 a 的实例中,此方法的所有调用都使用 origin Java虚拟机;其他虚拟机实例可能 使用不同的来源。

所以nanoTime() 可以很好地用于测量您的执行时间,因为测量值始终相同,并且会使用纳秒。

将开始时间设置为当前纳米时间。

start = System.nanoTime();

在循环结束时将结束时间设置为当前纳米时间

end = System.nanoTime();

要找出差异,即执行时间,只需像你一样减去。

为方便起见,您只需将getUserTime() 更改为返回System.nano()

例子:

//get integers m and n from user before this.
long start,end,time;
int[][] a = new int[m][n];
int[][] b = new int[m][n];
int[][] c= new int[m][n];

start = getUserTime();

for(int i = 0;i < m;i++)
{
    for(int j = 0;j < n;j++)
    {
        c[i][j] = a[i][j]+b[i][j];
    }
}
end = getUserTime();

// You could use Math.abs() here to handle the situation where 
// the values could be negative
time = end - start;

/** Get user time in nanoseconds. */
public long getUserTime() {
    return System.nanoTime()
}

【讨论】:

  • 错了... System.nanoTime() 不保证准确性... 不给你当前时间。
  • OP 不需要当前时间,他们需要程序执行的时间长度。 System.nanoTime() 非常适合。它将使用 JVM 的高分辨率时间源。
  • 返回的值表示自某个固定但任意的原始时间以来的纳秒(可能在将来,因此值可能为负数)。
  • 所以如果他得到:start=-100, end=-120, time=-120+100=-20 纳秒??
  • @Alboz,使用System.nanoTime 是测量经过时间的首选方法。看看这个答案:stackoverflow.com/questions/238920/…他们特别提到了使用currentTimeMillis的陷阱@
猜你喜欢
  • 1970-01-01
  • 2012-04-29
  • 1970-01-01
  • 2012-09-25
  • 2018-07-09
  • 2020-03-12
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多