背景
但我们需要统计代码的执行耗时时,总会用到
System.currentTimeMillis()
,如果需要统计的点位很多就会不停的加,有咩有工具类可以更直观和便捷的方式呢?当然有很多工具诸如 java.util.function、AutoCloseable等,本文将介绍StopWatch来实现。
public static void main(String[] args) throws InterruptedException {
Long startTime = System.currentTimeMillis();
// 业务代码
Thread.sleep(1000);
Long endTime = System.currentTimeMillis();
System.out.println("耗时:" + (endTime - startTime));
}
org.springframework.util之StopWatch
Spring提供的计时器StopWatch对于秒、毫秒为单位方便计时的程序,尤其是单线程、顺序执行程序的时间特性的统计输出支持比较好。
示例:
public static void main(String[] args) throws InterruptedException {
StopWatch sw = new StopWatch();
// Task1
sw.start("任务1");
Thread.sleep(1000 * 3);
System.out.println("currentTaskName:" + sw.currentTaskName());
sw.stop();
// Task2
sw.start("任务2");
Thread.sleep(1000 * 3);
System.out.println("currentTaskName:" + sw.currentTaskName());
sw.stop();
System.out.println("耗时详情打印" + sw.prettyPrint());
System.out.println("总耗时" + sw.shortSummary());
System.out.println("总耗时:" + sw.getTotalTimeMillis());
System.out.println("总数:" + sw.getTaskCount());
System.out.println("详情:" + sw.getTaskInfo());
}
输出结果:
currentTaskName:任务1
currentTaskName:任务2
耗时详情打印StopWatch '': running time = 5999596871 ns
---------------------------------------------
ns % Task name
---------------------------------------------
3000001996 050% 任务1
2999594875 050% 任务2
总耗时StopWatch '': running time = 5999596871 ns
总耗时:5999
总数:2
详情:[Lorg.springframework.util.StopWatch$TaskInfo;@52cc8049
使用总结:
StopWatch对象不是线程安全的。
一个StopWatch实例一次只能开启一个task。
在该task还没stop之前不能start一个新的task,必须在该task stop之后才能开启新的task。
apache commons lang3之StopWatch
apache commons lang3中StopWatch为计时提供了方便的 API。
示例:
public static void main(String[] args) throws InterruptedException {
//创建立即启动的秒表
StopWatch sw = StopWatch.createStarted();
Thread.sleep(1000);
sw.split();
System.out.println("耗时:" + sw.getTime());
// 在秒表上获取分段时间
System.out.println("耗时:" + sw.getSplitTime());
// 复位后, 重新计时
sw.reset();
sw.start();
Thread.sleep(1000);
System.out.println("重新开始耗时:" + sw.getTime());
// 暂停
sw.suspend();
Thread.sleep(1000);
// 恢复
sw.resume();
System.out.println("恢复执行耗时:" + sw.getTime());
Thread.sleep(1000);
sw.stop();
System.out.println("耗时" + sw.getTime(TimeUnit.SECONDS));
}
运行结果:
耗时:999
耗时:999
重新开始后到当前运行时间是:999
恢复后执行的时间是:999
花费的时间1
小结
代码千万行,安全第一行。用一种更优雅、简介的方式统计耗时,何乐而不为呢!
点赞 收藏 关注