使用getCurrentThreadUserTime()获取执行时间

时间:2014-10-07 19:48:17

标签: java execution-time

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

        //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,有时会返回15毫秒(都会不断重复)。

我不知道是否相信15ms或0.并且它们之间存在很大差异。 我知道准确性取决于操作系统,并不是真正的纳秒准确,但15毫秒是准确性问题。

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

非常感谢。

1 个答案:

答案 0 :(得分:3)

您应该使用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()
}