为什么System.nanoTime不准确?

时间:2013-12-21 23:02:22

标签: 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秒准确,精确地衡量该计划花了多长时间?

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

Syste.nanoTime()是完全准确的,因为你在一台不错的PC上工作,我认为你是。问题是在您第一次调用该方法之前的任何类型的初始化,包括JVM启动,堆栈设置,堆设置,大小数初始化需要一些时间。此外,如果您使用大量RAM并且几乎已满,启动时间可能更长。

相关问题