当前位置: 欣欣网 > 码农

今日代码 PK | 优雅统计耗时

2024-03-18码农

在开发中,接口的性能(特别是耗时)优化是必不可少的,

而优化的前提是搞清楚是哪个步骤比较耗时。

统计耗时的方式有很多,比如使用 System 时间戳,

示例代码如下:

/**
 * @author pine
 */

public classMain {
publicstaticvoidmain(String[] args) throws Exception{
// 任务1
longstart1 = System.currentTimeMillis();
Thread.sleep(1000);
longend1 = System.currentTimeMillis();
// 任务2
longstart2 = System.currentTimeMillis();
Thread.sleep(2000);
longend2 = System.currentTimeMillis();
// 打印出耗时
System.out.println(end1 - start1);
System.out.println(end2 - start2);
}
}


当然也有现成的工具实现,比如 Hutool StopWatch

不仅操作方便,打印的结果也更加易读、美观。

示例代码如下:

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.lang.Console;
/**
 * @author pine
 */

public classMain {
publicstaticvoidmain(String[] args) throws Exception{
StopWatchstopWatch = newStopWatch("任务名称");
// 任务1
stopWatch.start("任务一");
Thread.sleep(1000);
stopWatch.stop();
// 任务2
stopWatch.start("任务二");
Thread.sleep(2000);
stopWatch.stop();
// 打印出耗时
// StopWatch '任务名称': running time = 3010773584 ns
// ---------------------------------------------
// ns % Task name
// ---------------------------------------------
// 1005736375 33% 任务一
// 2005037209 67% 任务二
Console.log(stopWatch.prettyPrint());
}
}



大家更喜欢哪种呢?欢迎投票并在评论区留下自己的看法。

完整代码片段来源于代码小抄,欢迎点击进入小程序阅读!

在线访问:https://www.codecopy.cn/post/61ot1g

更多优质代码欢迎进入小程序查看!

往期推荐