使用spring-framework的StopWatch类优雅的输出执行耗时

      记录一段程序执行时间,最简单的方法就是打印当前时间与执行完时间的差值,其实这样并且不直观,目前spring-framework提供了一个StopWatch类可以做类似任务执行时间控制,也就是封装了一个对开始时间,结束时间记录工具。

 

例子

import org.springframework.util.StopWatch;
 
public class StopWatchTest {
 
    public static void main (String[] args) throws InterruptedException {
        StopWatch sw = new StopWatch();
        sw.start();
        //模拟程序执行
        Thread.sleep(1000);
        sw.stop();
        //输出程序执行的秒数
        System.out.println(sw.getTotalTimeMillis());
        System.out.println("+++++++++++++++++++++++++++++");

        //输出程序执行的毫秒数
        System.out.println(sw.getTotalTimeMillis());
        System.out.println("+++++++++++++++++++++++++++++");

        //优雅的格式打印结果,表格形式
        System.out.println(sw.prettyPrint());
        System.out.println("+++++++++++++++++++++++++++++");

        //返回简短的总耗时描述
        System.out.println(sw.shortSummary());
    }
}

输出

2002
+++++++++++++++++++++++++++++


2.002
+++++++++++++++++++++++++++++


StopWatch '': running time (millis) = 2002
-----------------------------------------
ms     %     Task name
-----------------------------------------
02002  100%  


+++++++++++++++++++++++++++++
StopWatch '': running time (millis) = 2002

是不是用起来简捷又方便。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章