Java 程序测量经过时间

编写一个 Java 程序,使用 System.currentTimeMillis 方法来测量经过的时间。currentTimeMillis 方法返回经过的挂钟时间。

package NumPrograms;

public class ElapsedTime1 {
	public static void main(String[] args) throws Exception {
		
		long startTime = System.currentTimeMillis();
		
		for(int i = 0; i < 6; i++)
		{
			Thread.sleep(100);
		}
		
		long endTime = System.currentTimeMillis();
		
		double elapsedtime = (endTime - startTime) / 1000.0;
		
		System.out.println("Elapsed Time = " + elapsedtime);
	}
}
Program to Measure Elapsed Time

此程序使用 System.nanoTime 方法测量经过的时间。nanoTime 方法返回纳秒为单位的结果。

package NumPrograms;

public class Example2 {

	public static void main(String[] args) throws Exception {
		
		long startTime = System.nanoTime();
		
		for(int i = 0; i < 5; i++)
		{
			Thread.sleep(100);
		}
		
		long endTime = System.nanoTime();
		
		double elapsedtime = (endTime - startTime) / 1000.0;
		
		System.out.println(elapsedtime);
	}
}
513317.972

Java 中,Instant 类表示时间线的实例。Instant.now 方法返回当前时间戳,我们在本程序中使用该方法来测量经过的时间。

package NumPrograms;

import java.time.Duration;
import java.time.Instant;

public class Example3 {

	public static void main(String[] args) throws Exception {
		
		Instant stTm = Instant.now();
		
		for(int i = 0; i < 5; i++)
		{
			Thread.sleep(100);
		}
		
		Instant edTm = Instant.now();
		
		double elapsedtime = Duration.between(stTm, edTm).toMillis();
		
		System.out.println(elapsedtime);
	}
}
509.0