java - 使用 getCurrentThread UserName() 获取执行时间

标签 java execution-time

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

        //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 性能。因此,如果可能的话,我希望编译器优化和操作系统上下文切换等的影响最小。

非常感谢。

最佳答案

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

来自文档:

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.

因此,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()
}

关于java - 使用 getCurrentThread UserName() 获取执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26244041/

相关文章:

java - 正则表达式: Replace except from specific characters and whitespace

java - 如何比较两个 eclipse 安装是否缺少功能?

python - 测量命令 : measure python script execution time

php - Yii2 无法在 Controller Action 中注册关机功能

javascript - 获得 Node.js 应用程序总执行时间的更好方法是什么?

java - 导航不同对象的复杂树的最佳方法是什么?

java - 如何防止外部xml文件被修改?

java - 使用 Java 将数据发送到 Microsoft Word 文档

正则表达式执行时间分析

multithreading - 是否有最小化线程数的搜索算法?