Java统计代码的执行时间的N种方法

目录
  • 方法一:System.currentTimeMillis
  • 方法二:System.nanoTime
  • 方法三:new Date
  • 方法四:Spring StopWatch
  • 方法五:commons-lang3 StopWatch
  • 方法六:Guava Stopwatch
  • 原理分析
    • 1.Spring StopWatch 原理分析
    • 2.Google Stopwatch 原理分析
  • 结论
  • 总结
  • 知识扩展—Stopwatch 让统计更方便

在日常开发中经常需要测试一些代码的执行时间,但又不想使用向 JMH(Java Microbenchmark Harness,Java 微基准测试套件)这么重的测试框架,所以本文就汇总了一些 Java 中比较常用的执行时间统计方法,总共包含以下 6 种,如下图所示:

方法一:System.currentTimeMillis

此方法为 Java 内置的方法,使用 System.currentTimeMillis 来执行统计的时间(统计单位:毫秒)(统计单位:毫秒),示例代码如下:

public class TimeIntervalTest {
    public static void main(String[] args) throws InterruptedException {
        // 开始时间
        long stime = System.currentTimeMillis();
        // 执行时间(1s)
        Thread.sleep(1000);
        // 结束时间
        long etime = System.currentTimeMillis();
        // 计算执行时间
        System.out.printf("执行时长:%d 毫秒.", (etime - stime));
    }
}

以上程序的执行结果为:

执行时长:1000 毫秒.

方法二:System.nanoTime

此方法为 Java 内置的方法,使用 System.nanoTime 来统计执行时间(统计单位:纳秒),它的执行方法和 System.currentTimeMillis 类似,示例代码如下:

public class TimeIntervalTest {
    public static void main(String[] args) throws InterruptedException {
        // 开始时间
        long stime = System.nanoTime();
        // 执行时间(1s)
        Thread.sleep(1000);
        // 结束时间
        long etime = System.nanoTime();
        // 计算执行时间
        System.out.printf("执行时长:%d 纳秒.", (etime - stime));
    }
}

以上程序的执行结果为:

执行时长:1000769200 纳秒.

小贴士:1 毫秒 = 100 万纳秒。

方法三:new Date

此方法也是 Java 的内置方法,在开始执行前 new Date() 创建一个当前时间对象,在执行结束之后 new Date() 一个当前执行时间,然后再统计两个 Date 的时间间隔,示例代码如下:

import java.util.Date;

public class TimeIntervalTest {
    public static void main(String[] args) throws InterruptedException {
        // 开始时间
        Date sdate = new Date();
        // 执行时间(1s)
        Thread.sleep(1000);
        // 结束时间
        Date edate = new Date();
        //  统计执行时间(毫秒)
        System.out.printf("执行时长:%d 毫秒." , (edate.getTime() - sdate.getTime()));
    }
}

以上程序的执行结果为:

执行时长:1000 毫秒.

方法四:Spring StopWatch

如果我们使用的是 Spring 或 Spring Boot 项目,可以在项目中直接使用 StopWatch 对象来统计代码执行时间,示例代码如下:

StopWatch stopWatch = new StopWatch();
// 开始时间
stopWatch.start();
// 执行时间(1s)
Thread.sleep(1000);
// 结束时间
stopWatch.stop();
// 统计执行时间(秒)
System.out.printf("执行时长:%d 秒.%n", stopWatch.getTotalTimeSeconds()); // %n 为换行
// 统计执行时间(毫秒)
System.out.printf("执行时长:%d 毫秒.%n", stopWatch.getTotalTimeMillis());
// 统计执行时间(纳秒)
System.out.printf("执行时长:%d 纳秒.%n", stopWatch.getTotalTimeNanos());

以上程序的执行结果为:

执行时长:0.9996313 秒. 执行时长:999 毫秒. 执行时长:999631300 纳秒.

小贴士:Thread#sleep 方法的执行时间稍有偏差,在 1s 左右都是正常的。

方法五:commons-lang3 StopWatch

如果我们使用的是普通项目,那我们可以用 Apache commons-lang3 中的 StopWatch 对象来实现时间统计,首先先添加 commons-lang3 的依赖:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.10</version>
</dependency>

然后编写时间统计代码:

import org.apache.commons.lang3.time.StopWatch;
import java.util.concurrent.TimeUnit;

public class TimeIntervalTest {
    public static void main(String[] args) throws InterruptedException {
        StopWatch stopWatch = new StopWatch();
        // 开始时间
        stopWatch.start();
        // 执行时间(1s)
        Thread.sleep(1000);
        // 结束时间
        stopWatch.stop();
        // 统计执行时间(秒)
        System.out.println("执行时长:" + stopWatch.getTime(TimeUnit.SECONDS) + " 秒.");
        // 统计执行时间(毫秒)
        System.out.println("执行时长:" + stopWatch.getTime(TimeUnit.MILLISECONDS) + " 毫秒.");
        // 统计执行时间(纳秒)
        System.out.println("执行时长:" + stopWatch.getTime(TimeUnit.NANOSECONDS) + " 纳秒.");
    }
}

以上程序的执行结果为:

执行时长:1 秒. 执行时长:1000 毫秒.

执行时长:1000555100 纳秒.

方法六:Guava Stopwatch

除了 Apache 的 commons-lang3 外,还有一个常用的 Java 工具包,那就是 Google 的 Guava,Guava 中也包含了  Stopwatch 统计类。首先先添加 Guava 的依赖:

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>29.0-jre</version>
</dependency>

然后编写时间统计代码:

import com.google.common.base.Stopwatch;
import java.util.concurrent.TimeUnit;

public class TimeIntervalTest {
    public static void main(String[] args) throws InterruptedException {
        // 创建并启动计时器
        Stopwatch stopwatch = Stopwatch.createStarted();
        // 执行时间(1s)
        Thread.sleep(1000);
        // 停止计时器
        stopwatch.stop();
        // 执行时间(单位:秒)
        System.out.printf("执行时长:%d 秒. %n", stopwatch.elapsed().getSeconds()); // %n 为换行
        // 执行时间(单位:毫秒)
        System.out.printf("执行时长:%d 豪秒.", stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }
}

以上程序的执行结果为:

执行时长:1 秒.

执行时长:1000 豪秒.

原理分析

本文我们从 Spring 和 Google 的 Guava 源码来分析一下,它们的 StopWatch 对象底层是如何实现的?

1.Spring StopWatch 原理分析

在 Spring 中 StopWatch 的核心源码如下:

package org.springframework.util;

import java.text.NumberFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.springframework.lang.Nullable;

public class StopWatch {
    private final String id;
    private boolean keepTaskList;
    private final List<StopWatch.TaskInfo> taskList;
    private long startTimeNanos;
    @Nullable
    private String currentTaskName;
    @Nullable
    private StopWatch.TaskInfo lastTaskInfo;
    private int taskCount;
    private long totalTimeNanos;

    public StopWatch() {
        this("");
    }

    public StopWatch(String id) {
        this.keepTaskList = true;
        this.taskList = new LinkedList();
        this.id = id;
    }

    public String getId() {
        return this.id;
    }

    public void setKeepTaskList(boolean keepTaskList) {
        this.keepTaskList = keepTaskList;
    }

    public void start() throws IllegalStateException {
        this.start("");
    }

    public void start(String taskName) throws IllegalStateException {
        if (this.currentTaskName != null) {
            throw new IllegalStateException("Can't start StopWatch: it's already running");
        } else {
            this.currentTaskName = taskName;
            this.startTimeNanos = System.nanoTime();
        }
    }

    public void stop() throws IllegalStateException {
        if (this.currentTaskName == null) {
            throw new IllegalStateException("Can't stop StopWatch: it's not running");
        } else {
            long lastTime = System.nanoTime() - this.startTimeNanos;
            this.totalTimeNanos += lastTime;
            this.lastTaskInfo = new StopWatch.TaskInfo(this.currentTaskName, lastTime);
            if (this.keepTaskList) {
                this.taskList.add(this.lastTaskInfo);
            }

            ++this.taskCount;
            this.currentTaskName = null;
        }
    }
    // .... 忽略其他代码
}

从上述 start() 和 stop() 的源码中可以看出,Spring 实现时间统计的本质还是使用了 Java 的内置方法 System.nanoTime() 来实现的。

2.Google Stopwatch 原理分析

Google Stopwatch 实现的核心源码如下:

public final class Stopwatch {
    private final Ticker ticker;
    private boolean isRunning;
    private long elapsedNanos;
    private long startTick;
    @CanIgnoreReturnValue
    public Stopwatch start() {
        Preconditions.checkState(!this.isRunning, "This stopwatch is already running.");
        this.isRunning = true;
        this.startTick = this.ticker.read();
        return this;
    }

    @CanIgnoreReturnValue
    public Stopwatch stop() {
        long tick = this.ticker.read();
        Preconditions.checkState(this.isRunning, "This stopwatch is already stopped.");
        this.isRunning = false;
        this.elapsedNanos += tick - this.startTick;
        return this;
    }
    // 忽略其他源码...
}

从上述源码中可以看出 Stopwatch 对象中调用了 ticker 类来实现时间统计的,那接下来我们进入 ticker 类的实现源码:

public abstract class Ticker {
    private static final Ticker SYSTEM_TICKER = new Ticker() {
        public long read() {
            return Platform.systemNanoTime();
        }
    };
    protected Ticker() {
    }
    public abstract long read();
    public static Ticker systemTicker() {
        return SYSTEM_TICKER;
    }
}
final class Platform {
    private static final Logger logger = Logger.getLogger(Platform.class.getName());
    private static final PatternCompiler patternCompiler = loadPatternCompiler();

    private Platform() {
    }

    static long systemNanoTime() {
        return System.nanoTime();
    }
    // 忽略其他源码...
}

从上述源码可以看出 Google Stopwatch 实现时间统计的本质还是调用了 Java 内置的 System.nanoTime() 来实现的。

结论

对于所有框架的 StopWatch 来说,其底层都是通过调用 Java 内置的 System.nanoTime() 得到两个时间,开始时间和结束时间,然后再通过结束时间减去开始时间来统计执行时间的。

总结

本文介绍了 6 种实现代码统计的方法,其中 3 种是 Java 内置的方法:

  • System.currentTimeMillis()
  • System.nanoTime()
  • new Date()

还介绍了 3 种常用框架 spring、commons-langs3、guava 的时间统计器 StopWatch。

在没有用到 spring、commons-langs3、guava 任意一种框架的情况下,推荐使用 System.currentTimeMillis() 或 System.nanoTime() 来实现代码统计,否则建议直接使用 StopWatch 对象来统计执行时间。

知识扩展—Stopwatch 让统计更方便

StopWatch 存在的意义是让代码统计更简单,比如 Guava 中 StopWatch 使用示例如下:

import com.google.common.base.Stopwatch;
import java.util.concurrent.TimeUnit;

public class TimeIntervalTest {
    public static void main(String[] args) throws InterruptedException {
        // 创建并启动计时器
        Stopwatch stopwatch = Stopwatch.createStarted();
        // 执行时间(1s)
        Thread.sleep(1000);
        // 停止计时器
        stopwatch.stop();
        // 执行统计
        System.out.printf("执行时长:%d 毫秒. %n",
                stopwatch.elapsed(TimeUnit.MILLISECONDS));
        // 清空计时器
        stopwatch.reset();
        // 再次启动统计
        stopwatch.start();
        // 执行时间(2s)
        Thread.sleep(2000);
        // 停止计时器
        stopwatch.stop();
        // 执行统计
        System.out.printf("执行时长:%d 秒. %n",
                stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }
}

我们可以使用一个 Stopwatch 对象统计多段代码的执行时间,也可以通过指定时间类型直接统计出对应的时间间隔,比如我们可以指定时间的统计单位,如秒、毫秒、纳秒等类型。

到此这篇关于Java统计代码的执行时间的6种方法的文章就介绍到这了,更多相关Java统计代码的执行时间内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • spring boot高并发下耗时操作的实现方法

    高并发下的耗时操作 高并发下,就是请求在一个时间点比较多时,很多写的请求打过来时,你的服务器承受很大的压力,当你的一个请求处理时间长时,这些请求将会把你的服务器线程耗尽,即你的主线程池里的线程将不会再有空闲状态的,再打过来的请求,将会是502了. 请求流程图 http1 http2 http3 thread1 thread2 thread3 解决方案 使用DeferredResult来实现异步的操作,当一个请求打过来时,先把它放到一个队列时,然后在后台有一个订阅者,有相关主题的消息发过来时,这个

  • spring boot aop 记录方法执行时间代码示例

    本文研究的主要是spring boot aop 记录方法执行时间的实现代码,具体如下. 为了性能调优,需要先统计出来每个方法的执行时间,直接在方法前后log输出太麻烦,可以用AOP来加入时间统计 添加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency&

  • Springboot之如何统计代码执行耗时时间

    目录 前言 正文 ① StopWatch ②  System.nanoTime() ③ new Date () ④  System.currentTimeMillis() 总结 前言 近日群里有萌新提到关于统计代码执行时间的事: 开始  System.currentTimeMillis()  减去  结束  System.currentTimeMillis()  等于  耗时 其实我个人感觉OK的,就这样就蛮好的,很多项目都是这样用的. 简简单单的挺好. 正文 ① StopWatch 第一种玩法

  • Java统计代码的执行时间的N种方法

    目录 方法一:System.currentTimeMillis 方法二:System.nanoTime 方法三:new Date 方法四:Spring StopWatch 方法五:commons-lang3 StopWatch 方法六:Guava Stopwatch 原理分析 1.Spring StopWatch 原理分析 2.Google Stopwatch 原理分析 结论 总结 知识扩展—Stopwatch 让统计更方便 在日常开发中经常需要测试一些代码的执行时间,但又不想使用向 JMH(J

  • java计算代码段执行时间的详细代码

    java里计算代码段执行时间可以有两种方法,一种是毫秒级别的计算,另一种是更精确的纳秒级别的计算. 一)毫秒级别计算时间 long startTime = System.currentTimeMillis(); /* 要计算执行时间的代码段 */ long endTime = System.currentTimeMillis(); System.out.println("代码段执行时间:" + (endTime - startTime) + "ms"); 二)更精确

  • Java计算代码段执行时间的详细过程

    目录 前言 场景 代码实现 MethodBody 接口定义 CalcExecuteTimeResult 运行结果实体 ExecuteTemplate 执行模板定义 CalcExecuteTimeContext 计算执行时间上下文 测试运行 前言 在日常开发功能时,同一种功能可能会有多种实现方式.我们需要做一个取舍. 最常见的条件就是性能.可读性.可维护性. 本篇文章,我们主要讨论“性能”. 场景 假设我们现在需要计算一段代码的运行时间. 最常见的写法是,在执行这段代码前,获得一下当前的时间戳,在

  • java统计字符串中指定元素出现次数方法

    本文实例讲解了统计文本中某个字符串出现的次数或字符串中指定元素出现的次数方法,分享给大家供大家参考,具体内容如下 运行效果图: 程序查找的上此文件带"a"的字符在多少次 具体代码如下 package com.zuidaima.util.string; import java.io.*; public class CountString { public static int count(String filename, String target) throws FileNotFoun

  • java 获取字节码文件的几种方法总结

    java 获取字节码文件的几种方法总结 在本文中,以Person类为例,将分别演示获取该类字节码文件的三种方式, 其具体思想及代码如下所示: public class Person { private int age; private String name; public Person() { System.out.println("person run"); } public Person(String name, int age) { this.age = age; this.n

  • java发送http get请求的两种方法(总结)

    长话短说,废话不说 一.第一种方式,通过HttpClient方式,代码如下: public static String httpGet(String url, String charset) throws HttpException, IOException { String json = null; HttpGet httpGet = new HttpGet(); // 设置参数 try { httpGet.setURI(new URI(url)); } catch (URISyntaxExc

  • Java编程求二叉树的镜像两种方法介绍

    给出一棵二叉树,求它的镜像,如下图:右边是二叉树是左边二叉树的镜像. 仔细分析这两棵树的特点,看看能不能总结出求镜像的步骤.这两棵树的根节点相同,但他们的左右两个子节点交换了位置.因此我们不妨先在树中交换根节点的两个子节点,就得到了下面一幅图中的第二颗树 解法1(递归) 思路1:如果当前节点为空,返回,否则交换该节点的左右节点,递归的对其左右节点进行交换处理. /*class TreeNode{ int val; TreeNode left=null; TreeNode right=null;

  • 基于Java数组实现循环队列的两种方法小结

    用java实现循环队列的方法: 1.添加一个属性size用来记录眼下的元素个数. 目的是当head=rear的时候.通过size=0还是size=数组长度.来区分队列为空,或者队列已满. 2.数组中仅仅存储数组大小-1个元素,保证rear转一圈之后不会和head相等.也就是队列满的时候.rear+1=head,中间刚好空一个元素. 当rear=head的时候.一定是队列空了. 队列(Queue)两端同意操作的类型不一样: 能够进行删除的一端称为队头,这样的操作也叫出队dequeue: 能够进行插

  • Java中获取键盘输入值的三种方法介绍

    程序开发过程中,需要从键盘获取输入值是常有的事,但Java它偏偏就没有像c语言给我们提供的scanf(),C++给我们提供的cin()获取键盘输入值的现成函数!Java没有提供这样的函数也不代表遇到这种情况我们就束手无策,请你看以下三种解决方法吧: 以下将列出几种方法: 方法一:从控制台接收一个字符,然后将其打印出来 public static void main(String [] args) throws IOException{ System.out.print("Enter a char

  • Java动态验证码单线设计的两种方法

    1.java的动态验证码我这里将介绍两种方法: 一:根据java本身提供的一种验证码的写法,这种呢只限于大家了解就可以了,因为java自带的模式编写的在实际开发中是没有意义的,所以只供学习一下就可以了,待会讲解的第二种呢就是我们需要掌握的一种模式了: 第一种的代码如下: import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import

随机推荐