使用nanoTime()计算时差,但得到负数

时间:2017-03-26 10:42:35

标签: nanotime

这是我的main中的代码,使用nanoTime()计算selectionSort()的时差:

    System.out.println("Start time :: " + test.start());
    test.selectionSort();
    System.out.println("End time :: " + test.end());
    System.out.println(test);
    System.out.print("Time took to run selectionSort() == ");
    System.out.println((test.getElapsedTime()) + " nanoseconds");

和我的start(),end()和getElapsedTime()方法是:

    public long start(){
    startTime = System.nanoTime();
    return startTime;
    }

    public long end(){
    endTime = System.nanoTime();
    return endTime;
    }

    public long getElapsedTime(){
    return end() - start();
    }

运行此程序后,输出为:

    5 2 9 7 4 3 0 1 6 8 
    Start time :: 915929737160723
    End time :: 915929737309925
    0 1 2 3 4 5 6 7 8 9 
    Time took to run selectionSort() == -5921 nanoseconds

当getElapsedTime()方法应该为正数时,为什么会返回负数?

2 个答案:

答案 0 :(得分:1)

由于getElapsedTime不会从startTime中减去endTime,但会在调用end()start()时重置它们。这两个呼叫几乎同时发生,并返回新的纳米时间。 start()显然恰好在稍后进行评估,因此结果是一个小的负数。

建议修复:

public long getElapsedTime() {
  return endTime - startTime;
}

答案 1 :(得分:0)

您必须将时间保存在变量中,如下所示:

startTime = System.nanoTime();
doThings(); //This is what you want to measure
elapsedTime = System.nanoTime() - startTime;
System.out.println((elapsedTime + " nanoseconds");