spring提供的计时器StopWatch对于秒、毫秒为单位方便计时的程序,尤其是单线程、顺序执行程序的时间特性的统计输出支持比较好。
一般为了记录某段代码的耗时排查问题会采用一下方法:
麻烦,看着比较low。使用StopWatch代码量骤减,而且让代码看着舒服多了。
StopWatch各计时器耗时及所占百分比(个人认为最有用的方法)简单应用示例:
import org.springframework.util.StopWatch;
import java.util.concurrent.TimeUnit;
@Test
public void testStopWatch() {
StopWatch stopWatch = new StopWatch();
stopWatch.start("task1");
for (int i = 0; i < 10000; i++) {
if(i%2==0) System.out.print(i);
}
stopWatch.stop();
stopWatch.start("task2");
for (int i = 0; i < 10000; i++) {
if(i%2==0) System.out.print(i);
}
stopWatch.stop();
stopWatch.start("task3");
try {
TimeUnit.MILLISECONDS.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
stopWatch.stop();
System.out.println("\n 消耗时长:"+stopWatch.prettyPrint());
}
输出结果:
StopWatch还有一些别的方法stopWatch.getTotalTimeMillis()获取总的耗时--第一个start到最后一个stop(本实例为10037);stopWatch.getLastTaskName()获取最后一个计时器的名称(本实例为task3);stopWatch.getTaskCount()获取计时器的数量(本实例为3)等等,自己可以按需使用。