java - 为什么 System.nanoTime 不准确?

标签 java runtime

import java.math.BigDecimal;
public class testtest {
    public static final BigDecimal TWO = new BigDecimal(2);
    public static final int digits = 1000;
    public static final BigDecimal TOLERANCE = BigDecimal.ONE.scaleByPowerOfTen(-digits);
    public static double MidpointMethod = 0;
    public static long MidpointMethod(int n) {
        BigDecimal k = new BigDecimal(n);
        BigDecimal a = BigDecimal.ONE; // set a to be one
        BigDecimal b = k; // set b to be two  
        long start = System.nanoTime(); // start the timer
        while(a.multiply(a).subtract(k).abs().compareTo(TOLERANCE) >= 0) { // while our decimals aren't close enough to the square root of two
            if(a.multiply(a).subtract(k).abs().compareTo(b.multiply(b).subtract(k).abs()) > 0)  // if a is farther from the square root of two than b
                a = a.add(b).divide(TWO); // set a to be the average of a and b
            else // if a is closer to the square root of two than b
                b = a.add(b).divide(TWO); // set b to be the average of a and b
        }
        return System.nanoTime() - start; // return the time taken
    }
    public static void main(String[] args) {
        System.out.println(MidpointMethod(2)/10e6);
    }

}

这个程序输出 6224.5209,但是当我运行它时,它运行了 20 多秒。为什么实际花了20多秒却显示6秒?

6 秒是否准确地衡量了程序花费的时间?

最佳答案

要将纳秒转换为毫秒(我假设您正在尝试),请除以 1e6,而不是 10e6。你的差距是 10 倍。

关于java - 为什么 System.nanoTime 不准确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20724477/

相关文章:

java - 在java中提取私钥

java - 如何使用索引使Web应用程序中的数据库访问更快?

java - 在Hibernate拦截器的afterTransactionBegin方法中执行查询

java - 最长回文子序列算法,时间分析

java - 为什么检索系统信息返回异常空点?

grails - 在gsp页面中使运行时计算失败

c++ - 在运行时设置 vector 类型

Java正则表达式匹配{{双花括号内的字符}}

c++ 如何在运行时通过错误代码给用户一个合适的异常?

算法 : Find recursive equation of divide and conquer algorithm