在日常的工作中,对某一段代码的执行耗时进行记录,属于相对常见的诉求,实现起来也很简单,不就是开始前记录一下当前时间戳,执行结束之后再记录一下当前时间戳,两者相减就可以得到我们想要的结果了
1. 时间戳差值法
这里主要借助的就是 System.currentTimeMillis()
来获取当前的时间戳(毫秒)
1.1 基本实现
先来看一下基本的使用姿势
// com.github.liuyueyi.hhui.trace.test.step.Step1#testCost
long start = System.currentTimeMillis();
// ... 这里省略掉需要计算耗时的业务逻辑
long end = System.currentTimeMillis();
System.out.println("cost: " + (end - start) + "ms");
上面这种写法比较简单直接,唯一的问题就是会有较多的重复冗余代码,特别是再一个执行链路中,存在较多的地方需要输出耗时时,就会发现代码块中,会出现大量的上面的代码块
有没有什么办法可以提炼一下呢?
- 通过函数方法来实现
1.2 公用方法
针对上面的写法,我们抽出一个耗时统计的公用方法,如下
// com.github.liuyueyi.hhui.trace.test.step.Step1#runWithTime
private void runWithTime(Runnable run) {
long start = System.currentTimeMillis();
try {
run.run();
} finally {
long end = System.currentTimeMillis();
System.out.println("cost: " + (end - start) + "ms");
}
}
当执行一个代码块不需要关注返回结果时,就可以通过下面这种方式进行耗时输出
private static Random random = new Random();
/**
* 随机睡眠一段时间
*
* @param max
*/
private static void randSleep(int max) {
int sleepMillSecond = random.nextInt(max);
try {
System.out.println("随机休眠 " + sleepMillSecond + "ms");
Thread.sleep(sleepMillSecond);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Test
public void testCost2() {
runWithTime(() -> {
randSleep(100);
});
}
执行以下上面的 testCost2 ,会得到如下的执行耗时输出
随机休眠 43ms
cost: 45ms
上面的公用方法适用于没有返回结果的耗时打印,但是现实中,当然还存在需要获取返回的场景,这个时候我们可以再封装一个公共方法,适用于有返回结果的场景
private <T> T supplyWithTime(Supplier<T> sup) {
long start = System.currentTimeMillis();
try {
return sup.get();
} finally {
long end = System.currentTimeMillis();
System.out.println("cost: " + (end - start) + "ms");
}
}
给出一个具体的使用demo
// com.github.liuyueyi.hhui.trace.test.step.Step1#testCost3
@Test
public void testCost3() {
回复