在查看代码执行时间时,我们常用System.currentTimeMillis()
long start = System.currentTimeMillis();
// 执行业务方法...
System.out.println("总耗时" + (System.currentTimeMillis() - start) + "(ms)");
spring 提供了一种简便的方式
1.StopWatch使用示例
public class TestStopwatch {
// 业务方法一
public static void execBusinessMethod1() throws InterruptedException {
Thread.sleep(100);
System.out.println(">>>>>>>>>>>>执行业务方法一<<<<<<<<<<<<<<<");
}
// 业务方法二
public static void execBusinessMethod2() throws InterruptedException {
Thread.sleep(200);
System.out.println(">>>>>>>>>>>>执行业务方法二<<<<<<<<<<<<<<<");
}
// 演示
public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start("方法一");
execBusinessMethod1();
stopWatch.stop();
stopWatch.start("方法二");
execBusinessMethod2();
stopWatch.stop();
stopWatch.start("代码块一");
for (int i = 0; i < 1000; ) {
i++;
}
stopWatch.stop();
System.out.println(stopWatch.prettyPrint()); // 美化输出
System.out.println("总耗时: " + stopWatch.getTotalTimeSeconds() + "(s)"); // 获取秒为单位的总耗时
}
}
2.StopWatch执行结果
>>>>>>>>>>>>执行业务方法一<<<<<<<<<<<<<<<
>>>>>>>>>>>>执行业务方法二<<<<<<<<<<<<<<<
StopWatch '': running time = 321757500 ns
---------------------------------------------
ns % Task name
---------------------------------------------
113107100 035% 方法一
208644500 065% 方法二
000005900 000% 代码块一
总耗时: 0.3217575(s)
3.StopWatch使用总结
-
StopWatch只作为调试代码的工具 相较于System.currentTimeMillis()简便一些,有格式化的统一输出;
-
StopWatch实例一次只能start一个task,不能同时start多个task;