排错手段-打印执行时间-StopWatch

正如标题,我们打印某些步骤或者方法的执行时间是因为程序执行这个方法时花费了较长的时间,但是我们不知道‘罪魁祸首’是哪一条语句。

以前的做法

以前的我为了找到哪条语句执行时间最长是这么做的:

//注释掉逻辑代码
final long begin = System.currentTimeMillis();
//Connection con = session.getConnection();
log.error(excelPath + "--->insert_01_" + (System.currentTimeMillis() - begin));
//con.setAutoCommit(false);
//Statement stat = con.createStatement();
//StringBuilder sb = new StringBuilder();
//sb.append("TRUNCATE `").append(dataInfos.getSheetName()).append("`;");
//stat.addBatch("TRUNCATE `" + dataInfos.getSheetName() + "`");
log.error(excelPath + "--->insert_02_" + (System.currentTimeMillis() - begin));
//String[][] datas = dataInfos.getDatas();
////删除无关代码
//try {
    log.error(excelPath + "--->insert_03_" + (System.currentTimeMillis() - begin));
//  stat.executeBatch();
    log.error(excelPath + "--->insert_04_" + (System.currentTimeMillis() - begin));
//} catch (BatchUpdateException ex) {

上面那段代码的执行结果就不展示了,一句话,就是看着比较乱,下面要介绍的是Spring框架的一个工具类StopWatch,看看它如何优雅的展示执行时间

更优雅的办法(StopWatch)

直接看代码,看看如何使用StopWatch

//注释掉逻辑代码
StopWatch stopWatch = new StopWatch();
//SqlSession session = GetFactory().getSessionFactory().openSession();
stopWatch.start("getConnection");
//Connection con = session.getConnection();
stopWatch.stop();
//Statement stat = con.createStatement();
//
stopWatch.start("addBatch");
//StringBuilder sb = new StringBuilder();
//sb.append("TRUNCATE `").append(dataInfos.getSheetName()).append("`;");
//
//stat.addBatch("TRUNCATE `" + dataInfos.getSheetName() + "`");
//String[][] datas = dataInfos.getDatas();
stopWatch.stop();
//
//log.info(sb.toString());
//try{
    stopWatch.start("executeBatch");
//  stat.executeBatch();
    stopWatch.stop();
    //这儿打印结果
    log.error(stopWatch.prettyPrint());
//} catch (BatchUpdateException ex)

打印结果

running time (millis) = 555
-----------------------------------------
ms     %     Task name
-----------------------------------------
00000  000%  getConnection
00000  000%  addBatch
00555  100%  executeBatch

总结

对比以前的做法和使用SpringStopWatch来打印日志

  1. 代码的编写来看个人觉得没有省下多少
  2. 但是展示结果来看无疑StopWatch,看着优雅舒服直观多了。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,977评论 6 342
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,067评论 19 139
  • 多年了 我在从前的山水中隐居 晴朗的夏夜 把蓬松的被子抱进屋里 星辰抖落了满地 拿一把雕花木梳 对着铜镜 梳理我银...
    粽少阅读 499评论 2 11
  • 穷则思变,差则思勤,没有比人更高的山没有比脚更长的路。
    思_3a2d阅读 277评论 0 0