查看原文
其他

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

编程导航-松柏 程序员鱼皮 2024-03-23

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

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

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

示例代码如下:

/**
 * @author pine
 */
public class Main {
    public static void main(String[] args) throws Exception{
        // 任务1
        long start1 = System.currentTimeMillis();
        Thread.sleep(1000);
        long end1 = System.currentTimeMillis();

        // 任务2
        long start2 = System.currentTimeMillis();
        Thread.sleep(2000);
        long end2 = System.currentTimeMillis();

        // 打印出耗时
        System.out.println(end1 - start1);
        System.out.println(end2 - start2);

    }
}

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

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

示例代码如下:

import cn.hutool.core.date.StopWatch;
import cn.hutool.core.lang.Console;

/**
 * @author pine
 */
public class Main {
    public static void main(String[] args) throws Exception{
        StopWatch stopWatch = new StopWatch("任务名称");

        // 任务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

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

往期推荐

今日代码 PK | 日期时间处理

今日代码大赏 | MyBatis-Plus 优雅查询

今日代码大赏 | 集合高阶操作

今日代码大赏 | 饿汉式单例模式

今日代码大赏 | 快速排序

继续滑动看下一个
向上滑动看下一个

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存