要获取经过时间,请首先获取开始时间。
long start = System.nanoTime();
现在,我们将在暂停5秒后获得结束时间。
long end = System.nanoTime();
对于经过的时间,找到结束和开始之间的时差。
long elapsed = end - start;
import java.util.concurrent.TimeUnit;
public class Demo {
public static void main(String[] args) throws InterruptedException {
long start = System.nanoTime();
TimeUnit.SECONDS.sleep(5);
long end = System.nanoTime();
long elapsed = end - start;
System.out.println("Execution time (nanoseconds) = " + elapsed);
}
}输出结果
Execution time (nanoseconds) = 5000820351