在平时的开发调试工做中,时常会遇到程序执行效率很是慢,经过通常的经验只能判断出部分逻辑有问题,但判断并不直观且效率较低。这时咱们就会用一些比较直观的方法来检查,好比看看某一段程序执行的时间,从而来判断是否比较耗时。比较经常使用的办法就是在程序开始时使用System.currentTimeMillis()记个时,而后再结束时计个时,再进行两个时间取差值就能够看出来了。java
long stime =System.currentTimeMillis(); // ... 程序代码 long etime =System.currentTimeMillis(); System.out.println("执行时间:"+(etime-stime));
但这种方法较麻烦,且若是同时要观察多个代码执行程序,要写较多代码。故如今能够直接使用 org.springframework.util.StopWatch 类来帮咱们统计时间。spring
它能够方便统计程序的每一段的执行时间,最后一块儿输出并显示每个的时间占比状况。pwa
public void run() throws Exception { StopWatch stopWatch = new StopWatch("demo1"); stopWatch.start("step1"); step1(); stopWatch.stop(); stopWatch.start("step2"); step2(); stopWatch.stop(); stopWatch.start("step3"); step3(); stopWatch.stop(); System.out.println(stopWatch.prettyPrint()); } private void step1() throws InterruptedException { Thread.sleep(100L); } private void step2() throws InterruptedException { Thread.sleep(850L); } private void step3() throws InterruptedException { Thread.sleep(2000L); }
输出结果:调试
StopWatch 'demo1': running time (millis) = 2972
-----------------------------------------
ms % Task name
-----------------------------------------
00108 004% step1
00861 029% step2
02003 067% step3code
从结果看出总执行时间为2972ms,将每一步的进行时间和占比,这样咱们就很容易能够排查哪个程序段执行的效率了,用起来特别方便。开发
虽然如今的方法已经很强大了,也很容易使用,但也要写好多代码并对被观察的代码段入侵太大,观察完后也还要一行一行删除代码,下一篇文章将介绍stopwatch的注解式用法,观察代码更少,敬请期待。io