在日常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执行的时间及占总共时间比。
本文介绍了在Java开发中,如何利用Spring框架的StopWatch工具类来监控代码块的运行时间,以便找出性能瓶颈。示例展示了StopWatch的使用方法,并通过调用prettyPrint()方法展示各部分代码的执行时间占比。
168万+

被折叠的 条评论
为什么被折叠?



