SpringBoot 统计代码执行耗时时间

该文对比了Java中不同时间测量方法的效果,包括使用newDate(),System.currentTimeMillis(),System.nanoTime(),Spring的StopWatch以及Java8的Instant.now(),展示了它们在计算执行时长中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、new Date()

    public static void main(String[] args) throws InterruptedException {
        Date dateStart = new Date();
        sleep();
        Date dateEnd = new Date();
        System.out.printf("执行时长: %d 毫秒",dateEnd.getTime() - dateStart.getTime());
    }

    public static void sleep() throws InterruptedException {
        Thread.sleep(2000);
    }

在这里插入图片描述

二、System.currentTimeMillis()

    public static void main(String[] args) throws InterruptedException {
        long start = System.currentTimeMillis();
        sleep();
        long end = System.currentTimeMillis();
        System.out.printf("执行时长: %d 毫秒",end - start);
    }

    public static void sleep() throws InterruptedException {
        Thread.sleep(2000);
    }

结果:
在这里插入图片描述

三、System.nanoTime()

new StopWatch() 的 内部方法

    public static void main(String[] args) throws InterruptedException {
        long start = System.nanoTime();
        sleep();
        long end = System.nanoTime();
        // 1毫秒 = 100纳秒
        System.out.printf("执行时长: %d 纳秒",end - start);
        System.out.printf("执行时长: %d 毫秒",end/1000000 - start/1000000);
    }

    public static void sleep() throws InterruptedException {
        Thread.sleep(2000);
    }

结果:
在这里插入图片描述

四、spring util 里面提供的 new StopWatch()

    public static void main(String[] args) throws InterruptedException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        sleep();
        stopWatch.stop();
        System.out.printf("执行时长: %d 毫秒",stopWatch.getTotalTimeMillis());
    }

    public static void sleep() throws InterruptedException {
        Thread.sleep(2000);
    }

结果:
在这里插入图片描述

五、java8 里面提供的 Instant.now()

    public static void main(String[] args) throws InterruptedException {
        Instant now = Instant.now();
        sleep();
        Instant end = Instant.now();
        System.out.printf("执行时长: %d 毫秒",end.toEpochMilli() - now.toEpochMilli());
    }

    public static void sleep() throws InterruptedException {
        Thread.sleep(2000);
    }

结果:
![在这里插入图片方法](https://i-blog.csdnimg.cn/blog_migrate/6b5a14c433079734d959bcbc4886fdb2.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子笙—望舒

整理编写不易,希望能支持支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值