Bootstrap

SpringBoot 统计代码执行耗时时间

一、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);
    }

结果:
![在这里插入图片方法](/image/aHR0cHM6Ly9pLWJsb2cuY3NkbmltZy5jbi9ibG9nX21pZ3JhdGUvNmI1YTE0YzQzMzA3OTczNGQ5NTliY2JjNDg4NmZkYjIucG5n

;