代码耗时检测stopWatch

在代码优化过程中,经常需要检测代码耗时,本篇介绍常见的几种

一、老方式System.currentTimeMillis

long startTime = System.currentTimeMillis();
// 你的业务代码
long endTime = System.currentTimeMillis();
long costTime = endTime -startTime;
System.err.println("代码耗时:" + costTime + " ms");

二、工具包中的秒表类

org.springframework.util.StopWatch、org.apache.commons.lang.time.StopWatch以及谷歌提供的guava中的秒表,本篇介绍spring包下的stopWatch

// 定义一个计数器
StopWatch stopWatch = new StopWatch("统一一组任务耗时");
// 统计任务一耗时
stopWatch.start("任务一");
Thread.sleep(1000);
stopWatch.stop();
// 统计任务二耗时
stopWatch.start("任务二");
Thread.sleep(2000);
stopWatch.stop();
// 统计任务二耗时
stopWatch.start("任务三");
Thread.sleep(3000);
stopWatch.stop();
// 打印出个任务耗时
String result = stopWatch.prettyPrint();
System.err.println(result);
// LOG.error(result);

输出结果:

image

耗时占比与总运行时间统一输出了

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容