Spring中使用StopWatch监控代码运行时间及性能比较

  在日常Java语言开发时,有时候需要监控方法中代码块的运行时长,从而确定性能点在哪,以及针对性的如何优化。利用springframework框架的工具类StopWatch可以快速方便的查看到每段代码运行的时间,准确确定性能瓶颈所在。

示例代码

    @Test
    public void test01() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("a");
        ApplicationContext ctx = new ClassPathXmlApplicationContext("com/springframework/chapter34/applicationContext.xml");
        UserManager userManager = ctx.getBean(UserManager.class);
        stopWatch.stop();
        stopWatch.start("b");
        userManager.login("ouyp", "123456");
        stopWatch.stop();
        System.out.println(stopWatch.prettyPrint());
    }

执行结果

StopWatch '': running time (millis) = 1142
-----------------------------------------
ms     %     Task name
-----------------------------------------
01105  097%  a
00037  003%  b

通过调用stopWatch.prettyPrint()我们可以知道任务a任务b执行的时间及占总共时间比。

参考链接

  1. StopWatch 监控Java代码运行时间和分析性能
  2. Spring中的计时器StopWatch

猜你喜欢

转载自blog.csdn.net/cockroach02/article/details/81490857