赞
踩
有时候为了统计性能耗时,会写几行代码计算一个方法或者sql执行消耗多久时间,打印出日志分析。下面写了3种计算代码执行完所消耗时间的方法。 (对于一些重要的业务场景需要监控的,可以把这个耗时结果写入数据量通过job去告警)
package com.walmart.aloha.paperless; import org.apache.commons.lang3.time.StopWatch; import org.springframework.util.StopWatch; import java.time.Duration; import java.time.Instant; import java.util.UUID; import java.util.concurrent.TimeUnit; /** * author yulisao * createDate 2023/9/11 */ public class Test { public static void main(String[] args) throws InterruptedException { /** * 1 通用方法 * 结束时间减去开始时间得到时间差 单位是毫秒 其他单位(比如秒、分、时等)需要自己去做除法运算转换 */ long beg = System.currentTimeMillis(); Thread.sleep(1000); // 用休眠代替你的业务逻辑执行完时间 long end = System.currentTimeMillis(); System.out.println("消耗时间:" + (end-beg)); // 1000 /** * 2 Duration用户(jdk1.8可使用,java.time包下的类) * 与上面写法类似 但时间差的单位不需要我们自己去作除法转换了,提供了对应的方案直接获取秒 还是 小时 ... */ Instant beg1 = Instant.now(); Thread.sleep(1000); Instant end1 = Instant.now(); Duration duration = Duration.between(beg1, end1); System.out.println("消耗时间:" + duration.toMillis()); // 1000 System.out.println("消耗时间:" + duration.toMinutes()); // 0 1秒不足1分钟所以是0 /** * 3 StopWatch * 第三方jar包提供: org.apache.commons commons-lang3 */ StopWatch watch = StopWatch.createStarted(); //创建后立即start,常用 Thread.sleep(1000); // 比如第1个sql查询 System.out.println("消耗时间:" + watch.getTime()); // 1000 默认毫秒 System.out.println("消耗时间:" + watch.getTime(TimeUnit.SECONDS)); // 1 可以指定单位 watch.reset(); // 重置 比如统计第2个sql查询耗时多久就不用重新创建一个StopWatch,直接在原基础上重置即可 watch.start(); // 重置后必须使用start方法重新开始计时 Thread.sleep(500); System.out.println("消耗时间:" + watch.getTime()); // 500 watch.suspend(); //暂停 Thread.sleep(6000); // 模拟第3个sql耗时, 暂停后的时间不计入 watch.resume(); //上面suspend,想要继续统计了需要恢复一下 Thread.sleep(400); // 模拟第4个sql耗时 恢复后的时间继续计入 System.out.println("消耗时间:" + watch.getTime()); // 500 + 400 = 900 统计了第2和4个sql查询的总耗时 watch.stop(); // 停止计时 /** * 4 StopWatch * 第三方jar包提供: org.springframework spring-core */ StopWatch sw = new StopWatch(UUID.randomUUID().toString()); // uuid作为计时器的名称 sw.start("第1个sql查询"); // 被计时的任务名称 Thread.sleep(1000); // 第1个sql查询 System.out.println("当前任务名称:" + sw.currentTaskName()); sw.stop(); sw.start("第2个sql查询"); // 被计时的任务名称 // 一次只能start一个任务,若上面那个任务没stop则下面这个不能start Thread.sleep(1000); // 第2个sql查询 System.out.println("当前任务名称:" + sw.currentTaskName()); sw.stop(); sw.start("第3个sql查询"); // 被计时的任务名称 Thread.sleep(1000); // 第3个sql查询 System.out.println("当前任务名称:" + sw.currentTaskName()); sw.stop(); // 分别统计了改方法种这3个sql各耗时多少 System.out.println(sw.prettyPrint()); // 按 耗时 占比 任务名称 进行列表展示 System.out.println("所有任务总耗时:" + sw.getTotalTimeMillis()); // 3000 System.out.println("任务总数:" + sw.getTaskCount()); // 3 } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。