为什么这些长篇被写为0或1?

时间:2017-02-17 18:02:19

标签: java filewriter

也许我的大脑今天不工作,但我只是想计算方法执行时间并将时间写入文件。出于某种原因,长值被写为0和1。以下是相关代码:

public static void main(String[] args) {
        //Reads numbers from file
        Scanner numberReader;
        //Writes execution times to file
        BufferedWriter writer;
        String heading = "Euclid (ms)\t\tPrime Factor (ms)\n";
        //Hold numbers from file
        int num1, num2;
        //Holds execution times
        long startTime, endTime, elapsedTime;

    try {
        //Reads file
        numberReader = new Scanner(new File(args[0]));
        //Opens the file to write to
        writer = new BufferedWriter(new FileWriter("comparison.txt", false));
        writer.write(heading);

        //While there are more numbers to read
        while(numberReader.hasNextInt()) {
            //Read the numbers
            num1 = numberReader.nextInt();
            num2 = numberReader.nextInt();

            System.out.println("Numbers: " + num1 + ", " + num2);

            //Run the first method and calculate execution time
            startTime = System.currentTimeMillis();
            System.out.println("Euclid GCD: " + euclid(num1, num2));
            endTime = System.currentTimeMillis();
            elapsedTime = endTime - startTime;
            //Write execution time to file
            writer.write(elapsedTime + "\n");

            //Run the second method and calculate execution time
            startTime = System.currentTimeMillis();
            System.out.println("Prime Factor GCD: " + primeFactor(num1, num2));
            endTime = System.currentTimeMillis();
            elapsedTime = endTime - startTime;
            //Write execution time to file
            writer.write(elapsedTime + "\n");
        }

        //Close the reader and writer
        numberReader.close();
        writer.close();
    }
    catch(Exception e) {
        e.printStackTrace();
    }
}

以下是示例输出:

Euclid (ms)     Prime Factor (ms)
1
1
0
0
0
0

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您尝试衡量的方法的执行大约为 micro - 秒。这些时间四舍五入到毫秒,因此任何小于500μs的时间都将输出为零。

您需要使用更高分辨率的计时器,例如System.nanoTime(),它可用于测量较短的间隔,但仅对经过的时间有用,而不是一天中的时间。即您可以减去两个值以获得经过的时间,但这些值本身与任何特定时间都不相关。

请注意,根据硬件的不同,您可能无法获得纳秒分辨率,但它会比毫秒更好。