使用System.currentTimeMillis()函数
long startMs = System.currentTimeMillis(); TimeUnit.SECONDS.sleep(2); System.out.println("timeCost: " + (System.currentTimeMillis() - startMs));//2001
使用System.nanoTime()函数
long start = System.nanoTime(); TimeUnit.SECONDS.sleep(2); long finish = System.nanoTime(); long timeElapsed = finish - start; System.out.println("timeElapsed: " + timeElapsed);//2000132106
在java8中使用Instant.now()函数
Instant start = Instant.now(); TimeUnit.SECONDS.sleep(2); Instant finish = Instant.now(); long timeElapsed = Duration.between(start, finish).toMillis(); System.out.println("timeElapsed: " + timeElapsed);//2001
使用apache.commons提供的StopWatch
import org.apache.commons.lang3.time.StopWatch; import java.util.concurrent.TimeUnit; public class StopWatchTest { public static void main(String[] args) throws InterruptedException { StopWatch started = StopWatch.createStarted(); TimeUnit.SECONDS.sleep(2); started.stop(); long time = started.getTime(); long nanoTime = started.getNanoTime(); long startTime = started.getStartTime(); System.out.println(time); System.out.println(nanoTime); System.out.println(startTime); } }
使用Spring 框架提供的StopWatch
import com.alibaba.fastjson.JSON; import org.springframework.util.StopWatch; import java.util.concurrent.TimeUnit; public class StopWatchTest { public static void main(String[] args) throws InterruptedException { StopWatch stopWatch = new StopWatch(); stopWatch.start("function1"); TimeUnit.SECONDS.sleep(1); // 模拟业务代码 stopWatch.stop(); stopWatch.start("function2"); TimeUnit.SECONDS.sleep(1); // 模拟业务代码 stopWatch.stop(); System.out.println(JSON.toJSONString(stopWatch.getTaskInfo())); System.out.println(stopWatch.prettyPrint()); } }