对Spring中StopWatch的理解

StopWatch是什么

StopWatch是Spring的一个工具类,用来记录一个或一组任务的执行时间。

StopWatch不是线程安全的。主要是验证开发环境的性能,不建议用在生产环境。

例子

  • 程序执行总时间

public class StopWatchTest {
    public static void main(String[] args) {
        StopWatch sw = new StopWatch();
        sw.start();
        try {
            Thread.sleep(1234L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        sw.stop();
        System.out.println("耗时:"+sw.getTotalTimeMillis());
    }
}
  • 每个任务执行时间

public class StopWatchTest {
    public static void main(String[] args) throws InterruptedException {
        StopWatch sw = new StopWatch();
        sw.start("起床");
        Thread.sleep(1234L);
        sw.stop();
        sw.start("吃饭");
        Thread.sleep(20L);
        sw.stop();
        sw.start("睡觉");
        Thread.sleep(2312L);
        sw.stop();
        System.out.println(sw.prettyPrint());
    }
}

输出:

StopWatch '': running time (millis) = 3571
-----------------------------------------
ms     %     Task name
-----------------------------------------
01234  035%  起床
00020  001%  吃饭
02317  065%  睡觉

一些思考

  • 封装的体现。将内部逻辑封装,通过对象调用api来实现功能。我们写util方法时也要这样。
  • 实现一个方法内多个处理逻辑时间监控。
发布了57 篇原创文章 · 获赞 39 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/SJZYLC/article/details/92795643