专栏名称: 程序员鱼皮
鹅厂全栈开发,持续分享编程技法和实用项目
目录
相关文章推荐
搜猪  ·  生猪现货日报|全国均价15.91元/公斤 ... ·  10 小时前  
51好读  ›  专栏  ›  程序员鱼皮

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

程序员鱼皮  · 公众号  ·  · 2024-03-18 12:09

正文

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

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

统计耗时的方式有很多,比如使用 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);

    }
}

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

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

示例代码如下:

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 优雅查询







请到「今天看啥」查看全文