StopWatch翻译过来的意思就是秒表,其做用也就像咱们平时使用的秒同样。spring中就有提供这个工具类(org.springframework.util.StopWatch)。spring
平常开发中,常常须要看方法各部分的耗时,一般的作法就是经过插桩的方式来统计耗时,以下:工具
1 long startTime = System.currentTimeMillis(); 2 Thread.sleep(1000); 3 long finishTime = System.currentTimeMillis(); 4 System.out.println("请求耗时:" + (finishTime - startTime));
若是有多个就要重复写多个,比较繁琐,这个时候就能够用StopWatch工具类。以下:spa
1 StopWatch sw = new StopWatch(); 2 3 sw.start("校验耗时"); 4 Thread.sleep(1000); 5 sw.stop(); 6 7 sw.start("组装报文耗时"); 8 Thread.sleep(2000); 9 sw.stop(); 10 11 sw.start("请求耗时"); 12 Thread.sleep(1000); 13 sw.stop(); 14 15 System.out.println(sw.prettyPrint()); 16 System.out.println(sw.getTotalTimeMillis());
即便须要加多个位置,也很方便,用prettyPrint方法,能够带格式自动输出各个任务的状况,以下:翻译
StopWatch还有一些其余的方法能够使用:code
prettyPrint:用自带格式输出全部任务信息。blog
getTaskInfo:获取全部任务的信息,即各个任务的名称和耗时。(若是想自定义输出一些内容,或者格式,能够从这里获取全部任务的信息)开发
getTotalTimeMillis:获取任务总耗时(毫秒)。get
getTotalTimeSeconds:获取任务总耗时(秒)。ast
getTaskCount:获取任务总数。class
getLastTaskName:获取最后一个任务的名称。
getLastTaskTimeMillis:获取最后一个任务的耗时(毫秒)。
getLastTaskInfo:获取最后一个任务的信息,即任务的名称和耗时。